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
10065950
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3417-alpha" /> </ItemGroup> </Project> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia <DFF> @@ -36,9 +36,8 @@ <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> - <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3417-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3466-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia
2
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10065951
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065952
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065953
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065954
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065955
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065956
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065957
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065958
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065959
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065960
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065961
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065962
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065963
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065964
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065965
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); textEditorModel.Dispose(); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); textEditorModel.Dispose(); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); textEditorModel.Dispose(); } } } <MSG> Applied review comments <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -164,7 +164,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -173,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -184,7 +183,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -193,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -206,7 +204,6 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); - textEditorModel.Dispose(); } [Test] @@ -215,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -223,7 +220,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -232,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -240,7 +236,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -249,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -258,7 +253,6 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); - textEditorModel.Dispose(); } [Test] @@ -267,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -280,7 +274,6 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); - textEditorModel.Dispose(); } [Test] @@ -289,7 +282,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -297,24 +290,30 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } [Test] @@ -323,7 +322,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; @@ -331,27 +330,34 @@ namespace AvaloniaEdit.Tests.TextMate document.BeginUpdate(); document.Insert(0, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); - Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); - Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); - Assert.IsNotNull(textEditorModel.InvalidRange); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); document.EndUpdate(); - Assert.IsNull(textEditorModel.InvalidRange); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); - textEditorModel.Dispose(); } } }
47
Applied review comments
41
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10065966
<NME> timsort.js <BEF> /** * Default minimum size of a run. */ const DEFAULT_MIN_MERGE = 32; /** * Minimum ordered subsequece required to do galloping. */ const DEFAULT_MIN_GALLOPING = 7; /** * Default tmp storage length. Can increase depending on the size of the * smallest run to merge. */ const DEFAULT_TMP_STORAGE_LENGTH = 256; /** * Sort an array in the range [lo, hi) using TimSort. * * @param {array} array - The array to sort. * @param {function=} compare - Item comparison function. Default is * alphabetical * @param {number} lo - First element in the range (inclusive). * @param {number} hi - Last element in the range. * comparator. */ export function sort( array, compare, lo, hi ) { if( !Array.isArray( array ) ) { throw new TypeError( 'Can only sort arrays' ); } /* * Handle the case where a comparison function is not provided. We do * lexicographic sorting */ if( !compare ) { compare = alphabeticalCompare; } else if( typeof compare !== 'function' ) { hi = lo; lo = compare; compare = alphabeticalCompare; } if( !lo ) { lo = 0; } if( !hi ) { hi = array.length; } let remaining = hi - lo; // The array is already sorted if( remaining < 2 ) { return; } let runLength = 0; // On small arrays binary sort can be used directly if( remaining < DEFAULT_MIN_MERGE ) { runLength = makeAscendingRun( array, lo, hi, compare ); binaryInsertionSort( array, lo, hi, lo + runLength, compare ); return; } let ts = new TimSort( array, compare ); let minRun = minRunLength( remaining ); do { runLength = makeAscendingRun( array, lo, hi, compare ); if( runLength < minRun ) { let force = remaining; if( force > minRun ) { force = minRun; } binaryInsertionSort( array, lo, lo + force, lo + runLength, compare ); runLength = force; } // Push new run and merge if necessary ts.pushRun( lo, runLength ); ts.mergeRuns(); // Go find next run remaining -= runLength; lo += runLength; } while( remaining !== 0 ); // Force merging of remaining runs ts.forceMergeRuns(); } /** * Default alphabetical comparison of items. * */ const POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9] /** * Estimate the logarithm base 10 of a small integer. * * @param {number} x - The integer to estimate the logarithm of. * @return {number} - The estimated logarithm of the integer. */ function log10(x) { if (x < 1e5) { if (x < 1e2) { return x < 1e1 ? 0 : 1; } if (x < 1e4) { return x < 1e3 ? 2 : 3; } return 4; } if (x < 1e7) { return x < 1e6 ? 5 : 6; } if (x < 1e9) { return x < 1e8 ? 7 : 8; } return 9; } /** * Default alphabetical comparison of items. * * @param {string|object|number} a - First element to compare. * @param {string|object|number} b - Second element to compare. * @return {number} - A positive number if a.toString() > b.toString(), a * negative number if .toString() < b.toString(), 0 otherwise. */ function alphabeticalCompare(a, b) { if (a === b) { return 0; } if (~~a === a && ~~b === b) { if (a === 0 || b === 0) { return a < b ? -1 : 1; } if (a < 0 || b < 0) { if (b >= 0) { return -1; } if (a >= 0) { return 1; } a = -a; b = -b; } const al = log10(a); const bl = log10(b); let t = 0; if (al < bl) { a *= POWERS_OF_TEN[bl - al - 1]; b /= 10; t = -1; } else if (al > bl) { b *= POWERS_OF_TEN[al - bl - 1]; a /= 10; t = 1; } if (a === b) { return t; } return a < b ? -1 : 1; } let aStr = String(a); let bStr = String(b); if (aStr === bStr) { return 0; } return aStr < bStr ? -1 : 1; } /** * Compute minimum run length for TimSort * * @param {number} n - The size of the array to sort. */ function minRunLength(n) { let r = 0; while (n >= DEFAULT_MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; } /** * Counts the length of a monotonically ascending or strictly monotonically * descending sequence (run) starting at array[lo] in the range [lo, hi). If * the run is descending it is made ascending. * * @param {array} array - The array to reverse. * @param {number} lo - First element in the range (inclusive). * @param {number} hi - Last element in the range. * @param {function} compare - Item comparison function. * @return {number} - The length of the run. */ function makeAscendingRun(array, lo, hi, compare) { let runHi = lo + 1; if (runHi === hi) { return 1; } // Descending if (compare(array[runHi++], array[lo]) < 0) { while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { runHi++; } reverseRun(array, lo, runHi); // Ascending } else { while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { runHi++; } } return runHi - lo; } /** * Reverse an array in the range [lo, hi). * * @param {array} array - The array to reverse. * @param {number} lo - First element in the range (inclusive). * @param {number} hi - Last element in the range. */ function reverseRun(array, lo, hi) { hi--; while (lo < hi) { let t = array[lo]; array[lo++] = array[hi]; array[hi--] = t; } } /** * Perform the binary sort of the array in the range [lo, hi) where start is * the first element possibly out of order. * * @param {array} array - The array to sort. * @param {number} lo - First element in the range (inclusive). * @param {number} hi - Last element in the range. * @param {number} start - First element possibly out of order. * @param {function} compare - Item comparison function. */ function binaryInsertionSort(array, lo, hi, start, compare) { if (start === lo) { start++; } for (; start < hi; start++) { let pivot = array[start]; // Ranges of the array where pivot belongs let left = lo; let right = start; /* * pivot >= array[i] for i in [lo, left) * pivot < array[i] for i in in [right, start) */ while (left < right) { let mid = (left + right) >>> 1; if (compare(pivot, array[mid]) < 0) { right = mid; } else { left = mid + 1; } } /* * Move elements right to make room for the pivot. If there are elements * equal to pivot, left points to the first slot after them: this is also * a reason for which TimSort is stable */ let n = start - left; // Switch is just an optimization for small arrays switch (n) { case 3: array[left + 3] = array[left + 2]; /* falls through */ case 2: array[left + 2] = array[left + 1]; /* falls through */ case 1: array[left + 1] = array[left]; break; default: while (n > 0) { array[left + n] = array[left + n - 1]; n--; } } array[left] = pivot; } } /** * Find the position at which to insert a value in a sorted range. If the range * contains elements equal to the value the leftmost element index is returned * (for stability). * * @param {number} value - Value to insert. * @param {array} array - The array in which to insert value. * @param {number} start - First element in the range. * @param {number} length - Length of the range. * @param {number} hint - The index at which to begin the search. * @param {function} compare - Item comparison function. * @return {number} - The index where to insert value. */ function gallopLeft(value, array, start, length, hint, compare) { let lastOffset = 0; let maxOffset = 0; let offset = 1; if (compare(value, array[start + hint]) > 0) { maxOffset = length - hint; while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Make offsets relative to start lastOffset += hint; offset += hint; // value <= array[start + hint] } else { maxOffset = hint + 1; while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Make offsets relative to start let tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } /* * Now array[start+lastOffset] < value <= array[start+offset], so value * belongs somewhere in the range (start + lastOffset, start + offset]. Do a * binary search, with invariant array[start + lastOffset - 1] < value <= * array[start + offset]. */ lastOffset++; while (lastOffset < offset) { let m = lastOffset + ((offset - lastOffset) >>> 1); if (compare(value, array[start + m]) > 0) { lastOffset = m + 1; } else { offset = m; } } return offset; } /** * Find the position at which to insert a value in a sorted range. If the range * contains elements equal to the value the rightmost element index is returned * (for stability). * * @param {number} value - Value to insert. * @param {array} array - The array in which to insert value. * @param {number} start - First element in the range. * @param {number} length - Length of the range. * @param {number} hint - The index at which to begin the search. * @param {function} compare - Item comparison function. * @return {number} - The index where to insert value. */ function gallopRight(value, array, start, length, hint, compare) { let lastOffset = 0; let maxOffset = 0; let offset = 1; if (compare(value, array[start + hint]) < 0) { maxOffset = hint + 1; while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Make offsets relative to start let tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; // value >= array[start + hint] } else { maxOffset = length - hint; while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } // Make offsets relative to start lastOffset += hint; offset += hint; } /* * Now array[start+lastOffset] < value <= array[start+offset], so value * belongs somewhere in the range (start + lastOffset, start + offset]. Do a * binary search, with invariant array[start + lastOffset - 1] < value <= * array[start + offset]. */ lastOffset++; while (lastOffset < offset) { let m = lastOffset + ((offset - lastOffset) >>> 1); if (compare(value, array[start + m]) < 0) { offset = m; } else { lastOffset = m + 1; } } return offset; } class TimSort { array = null; compare = null; minGallop = DEFAULT_MIN_GALLOPING; length = 0; tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH; stackLength = 0; runStart = null; runLength = null; stackSize = 0; constructor(array, compare) { this.array = array; this.compare = compare; this.length = array.length; if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) { this.tmpStorageLength = this.length >>> 1; } this.tmp = new Array(this.tmpStorageLength); this.stackLength = (this.length < 120 ? 5 : this.length < 1542 ? 10 : this.length < 119151 ? 19 : 40); this.runStart = new Array(this.stackLength); this.runLength = new Array(this.stackLength); } /** * Push a new run on TimSort's stack. * * @param {number} runStart - Start index of the run in the original array. * @param {number} runLength - Length of the run; */ pushRun(runStart, runLength) { this.runStart[this.stackSize] = runStart; this.runLength[this.stackSize] = runLength; this.stackSize += 1; } /** * Merge runs on TimSort's stack so that the following holds for all i: * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1] * 2) runLength[i - 2] > runLength[i - 1] */ mergeRuns() { while (this.stackSize > 1) { let n = this.stackSize - 2; if ((n >= 1 && this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1]) || (n >= 2 && this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1])) { if (this.runLength[n - 1] < this.runLength[n + 1]) { n--; } } else if (this.runLength[n] > this.runLength[n + 1]) { break; } this.mergeAt(n); } } /** * Merge all runs on TimSort's stack until only one remains. */ forceMergeRuns() { while (this.stackSize > 1) { let n = this.stackSize - 2; if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) { n--; } this.mergeAt(n); } } /** * Merge the runs on the stack at positions i and i+1. Must be always be called * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack). * * @param {number} i - Index of the run to merge in TimSort's stack. */ mergeAt(i) { let compare = this.compare; let array = this.array; let start1 = this.runStart[i]; let length1 = this.runLength[i]; let start2 = this.runStart[i + 1]; let length2 = this.runLength[i + 1]; this.runLength[i] = length1 + length2; if (i === this.stackSize - 3) { this.runStart[i + 1] = this.runStart[i + 2]; this.runLength[i + 1] = this.runLength[i + 2]; } this.stackSize--; /* * Find where the first element in the second run goes in run1. Previous * elements in run1 are already in place */ let k = gallopRight(array[start2], array, start1, length1, 0, compare); start1 += k; length1 -= k; if (length1 === 0) { return; } /* * Find where the last element in the first run goes in run2. Next elements * in run2 are already in place */ length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); if (length2 === 0) { return; } /* * Merge remaining runs. A tmp array with length = min(length1, length2) is * used */ if (length1 <= length2) { this.mergeLow(start1, length1, start2, length2); } else { this.mergeHigh(start1, length1, start2, length2); } } /** * Merge two adjacent runs in a stable way. The runs must be such that the * first element of run1 is bigger than the first element in run2 and the * last element of run1 is greater than all the elements in run2. * The method should be called when run1.length <= run2.length as it uses * TimSort temporary array to store run1. Use mergeHigh if run1.length > * run2.length. * * @param {number} start1 - First element in run1. * @param {number} length1 - Length of run1. * @param {number} start2 - First element in run2. * @param {number} length2 - Length of run2. */ mergeLow(start1, length1, start2, length2) { let compare = this.compare; let array = this.array; let tmp = this.tmp; let i = 0; for (i = 0; i < length1; i++) { tmp[i] = array[start1 + i]; } let cursor1 = 0; let cursor2 = start2; let dest = start1; array[dest++] = array[cursor2++]; if (--length2 === 0) { for (i = 0; i < length1; i++) { array[dest + i] = tmp[cursor1 + i]; } return; } if (length1 === 1) { for (i = 0; i < length2; i++) { array[dest + i] = array[cursor2 + i]; } array[dest + length2] = tmp[cursor1]; return; } let minGallop = this.minGallop; while (true) { let count1 = 0; let count2 = 0; let exit = false; do { if (compare(array[cursor2], tmp[cursor1]) < 0) { array[dest++] = array[cursor2++]; count2++; count1 = 0; if (--length2 === 0) { exit = true; break; } } else { array[dest++] = tmp[cursor1++]; count1++; count2 = 0; if (--length1 === 1) { exit = true; break; } } } while ((count1 | count2) < minGallop); if (exit) { break; } do { count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); if (count1 !== 0) { for (i = 0; i < count1; i++) { array[dest + i] = tmp[cursor1 + i]; } dest += count1; cursor1 += count1; length1 -= count1; if (length1 <= 1) { exit = true; break; } } array[dest++] = array[cursor2++]; if (--length2 === 0) { exit = true; break; } count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); if (count2 !== 0) { for (i = 0; i < count2; i++) { array[dest + i] = array[cursor2 + i]; } dest += count2; cursor2 += count2; length2 -= count2; if (length2 === 0) { exit = true; break; } } array[dest++] = tmp[cursor1++]; if (--length1 === 1) { exit = true; break; } minGallop--; } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); if (exit) { break; } if (minGallop < 0) { minGallop = 0; } minGallop += 2; } this.minGallop = minGallop; if (minGallop < 1) { this.minGallop = 1; } if (length1 === 1) { for (i = 0; i < length2; i++) { array[dest + i] = array[cursor2 + i]; } array[dest + length2] = tmp[cursor1]; } else if (length1 === 0) { throw new Error('mergeLow preconditions were not respected'); } else { for (i = 0; i < length1; i++) { array[dest + i] = tmp[cursor1 + i]; } } } /** * Merge two adjacent runs in a stable way. The runs must be such that the * first element of run1 is bigger than the first element in run2 and the * last element of run1 is greater than all the elements in run2. * The method should be called when run1.length > run2.length as it uses * TimSort temporary array to store run2. Use mergeLow if run1.length <= * run2.length. * * @param {number} start1 - First element in run1. * @param {number} length1 - Length of run1. * @param {number} start2 - First element in run2. * @param {number} length2 - Length of run2. */ mergeHigh(start1, length1, start2, length2) { let compare = this.compare; let array = this.array; let tmp = this.tmp; let i = 0; for (i = 0; i < length2; i++) { tmp[i] = array[start2 + i]; } let cursor1 = start1 + length1 - 1; let cursor2 = length2 - 1; let dest = start2 + length2 - 1; let customCursor = 0; let customDest = 0; array[dest--] = array[cursor1--]; if (--length1 === 0) { customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) { array[customCursor + i] = tmp[i]; } return; } if (length2 === 1) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) { array[customDest + i] = array[customCursor + i]; } array[dest] = tmp[cursor2]; return; } let minGallop = this.minGallop; while (true) { let count1 = 0; let count2 = 0; let exit = false; do { if (compare(tmp[cursor2], array[cursor1]) < 0) { array[dest--] = array[cursor1--]; count1++; count2 = 0; if (--length1 === 0) { exit = true; break; } } else { array[dest--] = tmp[cursor2--]; count2++; count1 = 0; if (--length2 === 1) { exit = true; break; } } } while ((count1 | count2) < minGallop); if (exit) { break; } do { count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); if (count1 !== 0) { dest -= count1; cursor1 -= count1; length1 -= count1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = count1 - 1; i >= 0; i--) { array[customDest + i] = array[customCursor + i]; } if (length1 === 0) { exit = true; break; } } } } } * @param {function=} compare - Item comparison function. Default is * alphabetical * @param {number} lo - First element in the range (inclusive). * @param {number} hi - Last element in the range. * comparator. */ export function sort(array, compare, lo, hi) { if (!Array.isArray(array)) { throw new TypeError('Can only sort arrays'); } /* * Handle the case where a comparison function is not provided. We do * lexicographic sorting */ if (!compare) { compare = alphabeticalCompare; } else if (typeof compare !== 'function') { hi = lo; lo = compare; compare = alphabeticalCompare; } if (!lo) { lo = 0; } if (!hi) { hi = array.length; } let remaining = hi - lo; // The array is already sorted if (remaining < 2) { return; } let runLength = 0; // On small arrays binary sort can be used directly if (remaining < DEFAULT_MIN_MERGE) { runLength = makeAscendingRun(array, lo, hi, compare); binaryInsertionSort(array, lo, hi, lo + runLength, compare); return; } let ts = new TimSort(array, compare); let minRun = minRunLength(remaining); do { runLength = makeAscendingRun(array, lo, hi, compare); if (runLength < minRun) { let force = remaining; if (force > minRun) { force = minRun; } binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); runLength = force; } // Push new run and merge if necessary ts.pushRun(lo, runLength); ts.mergeRuns(); // Go find next run remaining -= runLength; lo += runLength; } while (remaining !== 0); // Force merging of remaining runs ts.forceMergeRuns(); } <MSG> Satisfy ESLint. <DFF> @@ -14,85 +14,6 @@ const DEFAULT_MIN_GALLOPING = 7; */ const DEFAULT_TMP_STORAGE_LENGTH = 256; -/** - * Sort an array in the range [lo, hi) using TimSort. - * - * @param {array} array - The array to sort. - * @param {function=} compare - Item comparison function. Default is - * alphabetical - * @param {number} lo - First element in the range (inclusive). - * @param {number} hi - Last element in the range. - * comparator. - */ -export function sort( array, compare, lo, hi ) { - if( !Array.isArray( array ) ) { - throw new TypeError( 'Can only sort arrays' ); - } - - /* - * Handle the case where a comparison function is not provided. We do - * lexicographic sorting - */ - if( !compare ) { - compare = alphabeticalCompare; - - } else if( typeof compare !== 'function' ) { - hi = lo; - lo = compare; - compare = alphabeticalCompare; - } - - if( !lo ) { - lo = 0; - } - if( !hi ) { - hi = array.length; - } - - let remaining = hi - lo; - - // The array is already sorted - if( remaining < 2 ) { - return; - } - - let runLength = 0; - // On small arrays binary sort can be used directly - if( remaining < DEFAULT_MIN_MERGE ) { - runLength = makeAscendingRun( array, lo, hi, compare ); - binaryInsertionSort( array, lo, hi, lo + runLength, compare ); - return; - } - - let ts = new TimSort( array, compare ); - - let minRun = minRunLength( remaining ); - - do { - runLength = makeAscendingRun( array, lo, hi, compare ); - if( runLength < minRun ) { - let force = remaining; - if( force > minRun ) { - force = minRun; - } - - binaryInsertionSort( array, lo, lo + force, lo + runLength, compare ); - runLength = force; - } - // Push new run and merge if necessary - ts.pushRun( lo, runLength ); - ts.mergeRuns(); - - // Go find next run - remaining -= runLength; - lo += runLength; - - } while( remaining !== 0 ); - - // Force merging of remaining runs - ts.forceMergeRuns(); -} - /** * Default alphabetical comparison of items. * @@ -901,3 +822,82 @@ class TimSort { } } } + +/** + * Sort an array in the range [lo, hi) using TimSort. + * + * @param {array} array - The array to sort. + * @param {function=} compare - Item comparison function. Default is + * alphabetical + * @param {number} lo - First element in the range (inclusive). + * @param {number} hi - Last element in the range. + * comparator. + */ +export function sort( array, compare, lo, hi ) { + if( !Array.isArray( array ) ) { + throw new TypeError( 'Can only sort arrays' ); + } + + /* + * Handle the case where a comparison function is not provided. We do + * lexicographic sorting + */ + if( !compare ) { + compare = alphabeticalCompare; + + } else if( typeof compare !== 'function' ) { + hi = lo; + lo = compare; + compare = alphabeticalCompare; + } + + if( !lo ) { + lo = 0; + } + if( !hi ) { + hi = array.length; + } + + let remaining = hi - lo; + + // The array is already sorted + if( remaining < 2 ) { + return; + } + + let runLength = 0; + // On small arrays binary sort can be used directly + if( remaining < DEFAULT_MIN_MERGE ) { + runLength = makeAscendingRun( array, lo, hi, compare ); + binaryInsertionSort( array, lo, hi, lo + runLength, compare ); + return; + } + + let ts = new TimSort( array, compare ); + + let minRun = minRunLength( remaining ); + + do { + runLength = makeAscendingRun( array, lo, hi, compare ); + if( runLength < minRun ) { + let force = remaining; + if( force > minRun ) { + force = minRun; + } + + binaryInsertionSort( array, lo, lo + force, lo + runLength, compare ); + runLength = force; + } + // Push new run and merge if necessary + ts.pushRun( lo, runLength ); + ts.mergeRuns(); + + // Go find next run + remaining -= runLength; + lo += runLength; + + } while( remaining !== 0 ); + + // Force merging of remaining runs + ts.forceMergeRuns(); +}
79
Satisfy ESLint.
79
.js
js
mit
mziccard/node-timsort
10065967
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065968
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065969
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065970
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065971
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065972
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065973
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065974
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065975
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065976
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065977
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065978
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065979
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065980
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065981
<NME> HighlightingBrush.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 AvaloniaEdit.Rendering; using Avalonia.Media; using Avalonia.Media.Immutable; namespace AvaloniaEdit.Highlighting { /// <summary> /// A brush used for syntax highlighting. Can retrieve a real brush on-demand. /// </summary> public abstract class HighlightingBrush { /// <summary> /// Gets the real brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public abstract IBrush GetBrush(ITextRunConstructionContext context); /// <summary> /// Gets the color of the brush. /// </summary> /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { if (GetBrush(context) is SolidColorBrush scb) return scb.Color; return null; } } /// <summary> /// Highlighting brush implementation that takes a frozen brush. /// </summary> public sealed class SimpleHighlightingBrush : HighlightingBrush { private readonly ISolidColorBrush _brush; internal SimpleHighlightingBrush(ISolidColorBrush brush) { _brush = brush; } /// <summary> /// Creates a new HighlightingBrush with the specified color. /// </summary> public SimpleHighlightingBrush(Color color) : this(new ImmutableSolidColorBrush(color)) {} /// <inheritdoc/> public override IBrush GetBrush(ITextRunConstructionContext context) { return _brush; } /// <inheritdoc/> public override string ToString() { return _brush.ToString(); } /// <inheritdoc/> public override bool Equals(object obj) { SimpleHighlightingBrush other = obj as SimpleHighlightingBrush; if (other == null) return false; return _brush.Color.Equals(other._brush.Color); } /// <inheritdoc/> public override int GetHashCode() { return _brush.Color.GetHashCode(); } } } <MSG> Merge pull request #130 from whistyun/for-pr Change typecheck from SolidColorBrush to ISolidColorBrush <DFF> @@ -39,7 +39,7 @@ namespace AvaloniaEdit.Highlighting /// <param name="context">The construction context. context can be null!</param> public virtual Color? GetColor(ITextRunConstructionContext context) { - if (GetBrush(context) is SolidColorBrush scb) + if (GetBrush(context) is ISolidColorBrush scb) return scb.Color; return null; }
1
Merge pull request #130 from whistyun/for-pr
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065982
<NME> README.md <BEF> # Lumen Passport [![Build Status](https://travis-ci.org/dusterio/lumen-passport.svg)](https://travis-ci.org/dusterio/lumen-passport) [![Code Climate](https://codeclimate.com/github/dusterio/lumen-passport/badges/gpa.svg)](https://codeclimate.com/github/dusterio/lumen-passport/badges) [![Total Downloads](https://poser.pugx.org/dusterio/lumen-passport/d/total.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Stable Version](https://poser.pugx.org/dusterio/lumen-passport/v/stable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Unstable Version](https://poser.pugx.org/dusterio/lumen-passport/v/unstable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![License](https://poser.pugx.org/dusterio/lumen-passport/license.svg)](https://packagist.org/packages/dusterio/lumen-passport) > Making Laravel Passport work with Lumen ## Introduction It's a simple service provider that makes **Laravel Passport** work with **Lumen**. ## Installation First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet. Then install **Lumen Passport**: ```bash composer require dusterio/lumen-passport ``` Or if you prefer, edit `composer.json` manually and run then `composer update`: ```json { "require": { "dusterio/lumen-passport": "^0.3.5" } } ```json { "require": { "dusterio/lumen-passport": "~0.1" } } ``` /** @file bootstrap/app.php */ // Enable Facades $app->withFacades(); // Enable Eloquent $app->withEloquent(); // Enable auth middleware (shipped with Lumen) $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]); // Register two service providers, Laravel Passport and Lumen adapter $app->register(Laravel\Passport\PassportServiceProvider::class); $app->register(Dusterio\LumenPassport\PassportServiceProvider::class); ``` ### Laravel Passport ^7.3.2 and newer On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows: ```php /** @file bootstrap/app.php */ //$app = new Laravel\Lumen\Application( // dirname(__DIR__) //); $app = new \Dusterio\LumenPassport\Lumen7Application( dirname(__DIR__) ); ``` \* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._ ### Migrate and install Laravel Passport ```bash # Create new tables for Passport php artisan migrate # Install encryption keys and other stuff for Passport php artisan passport:install ``` It will output the Personal access client ID and secret, and the Password grand client ID and secret. \* _Note: Save the secrets in a safe place, you'll need them later to request the access tokens._ ## Configuration ### Configure Authentication Edit `config/auth.php` to suit your needs. A simple example: ```php /** @file config/auth.php */ return [ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \App\Models\User::class ] ], ]; ``` \* _Note: Lumen 7.x and older uses `\App\User::class`_ Load the config since Lumen doesn't load config files automatically: ```php /** @file bootstrap/app.php */ $app->configure('auth'); ``` ### Registering Routes Next, you should call the `LumenPassport::routes` method within the `boot` method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens: ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); /* rest of boot */ } } ``` ### User model Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait. ```php /** @file app/Models/User.php */ use Laravel\Passport\HasApiTokens; class User extends Model implements AuthenticatableContract, AuthorizableContract { use HasApiTokens, Authenticatable, Authorizable, HasFactory; /* rest of the model */ } ``` ## Usage You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport). ### Curl example with username and password authentication First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests. ```bash # Request curl --location --request POST '{{APP_URL}}/oauth/token' \ --header 'Content-Type: application/json' \ --data-raw '{ "grant_type": "password", "client_id": "{{CLIENT_ID}}", "client_secret": "{{CLIENT_SECRET}}", "username": "{{USER_EMAIL}}", "password": "{{USER_PASSWORD}}", "scope": "*" }' ``` ```json { "token_type": "Bearer", "expires_in": 31536000, "access_token": "******", "refresh_token": "******" } ``` And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**. ```php /** @file routes/web.php */ $router->get('/ping', ['middleware' => 'auth', fn () => 'pong']); ``` ```bash # Request curl --location --request GET '{{APP_URL}}/ping' \ --header 'Authorization: Bearer {{ACCESS_TOKEN}}' ``` ```html pong ``` ### Installed routes This package mounts the following routes after you call `routes()` method, all of them belongs to the namespace `\Laravel\Passport\Http\Controllers`: Verb | Path | Controller | Action | Middleware --- | --- | --- | --- | --- POST | /oauth/token | AccessTokenController | issueToken | - GET | /oauth/tokens | AuthorizedAccessTokenController | forUser | auth DELETE | /oauth/tokens/{token_id} | AuthorizedAccessTokenController | destroy | auth POST | /oauth/token/refresh | TransientTokenController | refresh | auth GET | /oauth/clients | ClientController | forUser | auth POST | /oauth/clients | ClientController | store | auth PUT | /oauth/clients/{client_id} | ClientController | update | auth DELETE | /oauth/clients/{client_id} | ClientController | destroy | auth GET | /oauth/scopes | ScopeController | all | auth GET | /oauth/personal-access-tokens | PersonalAccessTokenController | forUser | auth POST | /oauth/personal-access-tokens | PersonalAccessTokenController | store | auth DELETE | /oauth/personal-access-tokens/{token_id} | PersonalAccessTokenController | destroy | auth \* _Note: some of the **Laravel Passport**'s routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present._ ## Extra features There are a couple of extra features that aren't present in **Laravel Passport** ### Prefixing Routes You can add that into an existing group, or add use this route registrar independently like so; ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); /* rest of boot */ } } ``` ### Multiple tokens per client Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers simultaneously. Currently **Laravel Passport** does not allow that. ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); LumenPassport::allowMultipleTokens(); /* rest of boot */ } } ``` ### Different TTLs for different password clients **Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users). Simply do the following in your service provider: ```php /** @file app/Providers/AuthServiceProvider.php */ use Carbon\Carbon; use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); $client_id = '1'; LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id); /* rest of boot */ } } ``` If you don't specify client Id, it will simply fall back to Laravel Passport implementation. ### Purge expired tokens ```bash php artisan passport:purge ``` Simply run it to remove expired refresh tokens and their corresponding access tokens from the database. ## Error and issue resolution Instead of opening a new issue, please see if someone has already had it and it has been resolved. If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md). ## Video tutorials I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps. Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :) ## License The MIT License (MIT) Copyright (c) 2016 Denis Mysenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <MSG> Merge pull request #22 from ssgtcookie/patch-1 Update README.md <DFF> @@ -34,7 +34,7 @@ Or if you prefer, edit `composer.json` manually: ```json { "require": { - "dusterio/lumen-passport": "~0.1" + "dusterio/lumen-passport": "^0.1.7" } } ```
1
Merge pull request #22 from ssgtcookie/patch-1
1
.md
md
mit
dusterio/lumen-passport
10065983
<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 (590 bytes). [![Build Status](https://travis-ci.org/muicss/loadjs.svg?branch=master)](https://travis-ci.org/muicss/loadjs) [![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#info=devDependencies) ## 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 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() { }); ``` ## Development Dependencies * nodejs (http://nodejs.org/) * npm (https://www.npmjs.org/) ## Directory structure <pre> ```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 */ | └── loadjs.js ├── test/ </pre> }) .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> @@ -4,7 +4,6 @@ LoadJS is a tiny async loader for modern browsers (590 bytes). -[![Build Status](https://travis-ci.org/muicss/loadjs.svg?branch=master)](https://travis-ci.org/muicss/loadjs) [![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#info=devDependencies) @@ -111,11 +110,6 @@ loadjs.ready('jquery', function() { }); ``` -## Development Dependencies - - * nodejs (http://nodejs.org/) - * npm (https://www.npmjs.org/) - ## Directory structure <pre> @@ -133,3 +127,49 @@ loadjs/ | └── loadjs.js ├── test/ </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 + $ ./node_modules/.bin/gulp 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 + $ ./node_modules/.bin/http-server -p 3000 + ``` + + Then visit http://localhost:3000/examples + +## Run tests + +To run the browser tests first build the `loadjs` library: + +```bash +$ ./node_modules/.bin/gulp build-test +``` + +Then visit http://localhost:3000/test
46
Update README.md
6
.md
md
mit
muicss/loadjs
10065984
<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 (590 bytes). [![Build Status](https://travis-ci.org/muicss/loadjs.svg?branch=master)](https://travis-ci.org/muicss/loadjs) [![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#info=devDependencies) ## 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 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() { }); ``` ## Development Dependencies * nodejs (http://nodejs.org/) * npm (https://www.npmjs.org/) ## Directory structure <pre> ```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 */ | └── loadjs.js ├── test/ </pre> }) .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> @@ -4,7 +4,6 @@ LoadJS is a tiny async loader for modern browsers (590 bytes). -[![Build Status](https://travis-ci.org/muicss/loadjs.svg?branch=master)](https://travis-ci.org/muicss/loadjs) [![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#info=devDependencies) @@ -111,11 +110,6 @@ loadjs.ready('jquery', function() { }); ``` -## Development Dependencies - - * nodejs (http://nodejs.org/) - * npm (https://www.npmjs.org/) - ## Directory structure <pre> @@ -133,3 +127,49 @@ loadjs/ | └── loadjs.js ├── test/ </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 + $ ./node_modules/.bin/gulp 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 + $ ./node_modules/.bin/http-server -p 3000 + ``` + + Then visit http://localhost:3000/examples + +## Run tests + +To run the browser tests first build the `loadjs` library: + +```bash +$ ./node_modules/.bin/gulp build-test +``` + +Then visit http://localhost:3000/test
46
Update README.md
6
.md
md
mit
muicss/loadjs
10065985
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065986
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065987
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065988
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065989
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065990
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065991
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065992
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065993
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065994
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065995
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065996
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065997
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065998
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10065999
<NME> SelectionMouseHandler.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.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetPointerPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Revert "fix" This reverts commit 600ef65afa75b494a44d8fc6c6fa28183b16a67f. <DFF> @@ -16,13 +16,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using Avalonia; -using Avalonia.Input; -using AvaloniaEdit.Document; -using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; +using Avalonia; +using AvaloniaEdit.Document; +using AvaloniaEdit.Utils; +using Avalonia.Input; namespace AvaloniaEdit.Editing { @@ -392,111 +392,111 @@ namespace AvaloniaEdit.Editing private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { - if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed) - { - TextArea.Cursor = Cursor.Parse("IBeam"); + TextArea.Cursor = Cursor.Parse("IBeam"); - var pointer = e.GetPointerPoint(TextArea); + var pointer = e.GetPointerPoint(TextArea); - _mode = SelectionMode.None; - if (!e.Handled) + _mode = SelectionMode.None; + if (!e.Handled) + { + var modifiers = e.KeyModifiers; + var shift = modifiers.HasFlag(KeyModifiers.Shift); + if (_enableTextDragDrop && !shift) { - var modifiers = e.KeyModifiers; - var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + var offset = GetOffsetFromMousePosition(e, out _, out _); + if (TextArea.Selection.Contains(offset)) { - var offset = GetOffsetFromMousePosition(e, out _, out _); - if (TextArea.Selection.Contains(offset)) + if (TextArea.CapturePointer(e.Pointer)) { - if (TextArea.CapturePointer(e.Pointer)) - { - _mode = SelectionMode.PossibleDragStart; - _possibleDragStartMousePos = e.GetPosition(TextArea); - } - e.Handled = true; - return; + _mode = SelectionMode.PossibleDragStart; + _possibleDragStartMousePos = e.GetPosition(TextArea); } + e.Handled = true; + return; } + } + + var oldPosition = TextArea.Caret.Position; + SetCaretOffsetToMousePosition(e); - var oldPosition = TextArea.Caret.Position; - SetCaretOffsetToMousePosition(e); + if (!shift) + { + TextArea.ClearSelection(); + } - if (!shift) + if (TextArea.CapturePointer(e.Pointer)) + { + if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { - TextArea.ClearSelection(); + _mode = SelectionMode.Rectangular; + if (shift && TextArea.Selection is RectangleSelection) + { + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); + } } - - if (TextArea.CapturePointer(e.Pointer)) + else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { - if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) + _mode = SelectionMode.WholeWord; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.Rectangular; - if (shift && TextArea.Selection is RectangleSelection) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 + } + else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + { + _mode = SelectionMode.Normal; + if (shift && !(TextArea.Selection is RectangleSelection)) { - _mode = SelectionMode.WholeWord; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } - else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 + } + else + { + SimpleSegment startWord; + + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + + if (e.ClickCount == 3) { - _mode = SelectionMode.Normal; - if (shift && !(TextArea.Selection is RectangleSelection)) - { - TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); - } + _mode = SelectionMode.WholeLine; + startWord = GetLineAtMousePosition(e); } else { - SimpleSegment startWord; - - if (e.ClickCount == 3) - { - _mode = SelectionMode.WholeLine; - startWord = GetLineAtMousePosition(e); - } - else - { - _mode = SelectionMode.WholeWord; - startWord = GetWordAtMousePosition(e); - } - - if (startWord == SimpleSegment.Invalid) - { - _mode = SelectionMode.None; - TextArea.ReleasePointerCapture(e.Pointer); - return; - } - if (shift && !TextArea.Selection.IsEmpty) + _mode = SelectionMode.WholeWord; + startWord = GetWordAtMousePosition(e); + } + + if (startWord == SimpleSegment.Invalid) + { + _mode = SelectionMode.None; + TextArea.ReleasePointerCapture(e.Pointer); + return; + } + if (shift && !TextArea.Selection.IsEmpty) + { + if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { - if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); - } - else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) - { - TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); - } - _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } - else + else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { - TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); - _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); + TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } + _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); + } + else + { + TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); + _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } - e.Handled = true; } - } - } + e.Handled = true; + } + } #endregion #region LeftButtonClick @@ -684,7 +684,7 @@ namespace AvaloniaEdit.Editing else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); - if (newWord != SimpleSegment.Invalid && _startWord != null) + if (newWord != SimpleSegment.Invalid &&_startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset),
82
Revert "fix"
82
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066000
<NME> jsgrid.load-indicator.js <BEF> (function(jsGrid, $, undefined) { function LoadIndicator(config) { this._init(config); } LoadIndicator.prototype = { container: "body", message: "Loading...", shading: true, _init: function(config) { $.extend(true, this, config); }, show: function() { }, hide: function() { } }; jsGrid.LoadIndicator = LoadIndicator; }(jsGrid, jQuery)); <MSG> LoadIndicator: Rendering <DFF> @@ -10,16 +10,69 @@ message: "Loading...", shading: true, + zIndex: 1000, + shaderClass: "jsgrid-load-shader", + loadPanelClass: "jsgrid-load-panel", + _init: function(config) { $.extend(true, this, config); + + this._initContainer(); + this._initShader(); + this._initLoadPanel(); + }, + + _initContainer: function() { + this._container = $(this.container).css("position", "relative"); + }, + + _initShader: function() { + if(!this.shading) + return; + + this._shader = $("<div>").addClass(this.shaderClass) + .hide() + .css({ + position: "absolute", + top: 0, + right: 0, + bottom: 0, + left: 0, + zIndex: this.zIndex + }) + .appendTo(this._container); + }, + + _initLoadPanel: function() { + this._loadPanel = $("<div>").addClass(this.loadPanelClass) + .text(this.message) + .hide() + .css({ + position: "absolute", + top: "50%", + left: "50%", + zIndex: this.zIndex + }) + .appendTo(this._container); }, show: function() { + var $loadPanel = this._loadPanel.show(); + var actualWidth = $loadPanel.outerWidth(); + var actualHeight = $loadPanel.outerHeight(); + + $loadPanel.css({ + marginTop: -actualHeight / 2, + marginLeft: -actualWidth / 2 + }); + + this._shader.show(); }, hide: function() { - + this._loadPanel.hide(); + this._shader.hide(); } };
54
LoadIndicator: Rendering
1
.js
load-indicator
mit
tabalinas/jsgrid
10066001
<NME> jsgrid.load-indicator.js <BEF> (function(jsGrid, $, undefined) { function LoadIndicator(config) { this._init(config); } LoadIndicator.prototype = { container: "body", message: "Loading...", shading: true, _init: function(config) { $.extend(true, this, config); }, show: function() { }, hide: function() { } }; jsGrid.LoadIndicator = LoadIndicator; }(jsGrid, jQuery)); <MSG> LoadIndicator: Rendering <DFF> @@ -10,16 +10,69 @@ message: "Loading...", shading: true, + zIndex: 1000, + shaderClass: "jsgrid-load-shader", + loadPanelClass: "jsgrid-load-panel", + _init: function(config) { $.extend(true, this, config); + + this._initContainer(); + this._initShader(); + this._initLoadPanel(); + }, + + _initContainer: function() { + this._container = $(this.container).css("position", "relative"); + }, + + _initShader: function() { + if(!this.shading) + return; + + this._shader = $("<div>").addClass(this.shaderClass) + .hide() + .css({ + position: "absolute", + top: 0, + right: 0, + bottom: 0, + left: 0, + zIndex: this.zIndex + }) + .appendTo(this._container); + }, + + _initLoadPanel: function() { + this._loadPanel = $("<div>").addClass(this.loadPanelClass) + .text(this.message) + .hide() + .css({ + position: "absolute", + top: "50%", + left: "50%", + zIndex: this.zIndex + }) + .appendTo(this._container); }, show: function() { + var $loadPanel = this._loadPanel.show(); + var actualWidth = $loadPanel.outerWidth(); + var actualHeight = $loadPanel.outerHeight(); + + $loadPanel.css({ + marginTop: -actualHeight / 2, + marginLeft: -actualWidth / 2 + }); + + this._shader.show(); }, hide: function() { - + this._loadPanel.hide(); + this._shader.hide(); } };
54
LoadIndicator: Rendering
1
.js
load-indicator
mit
tabalinas/jsgrid
10066002
<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) $result = this.rowRenderer(item, itemIndex); } else { $result = $("<tr>").addClass(this._getRowClasses(item, itemIndex)); this._renderCells($result, item); } $result.data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item, .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) { this.rowClick({ item: item, itemIndex: itemIndex, event: e }); }, this)) .on("dblclick", $.proxy(function(e) { this.rowDoubleClick({ item: item, 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> Core: Add css classes to row rendered with custom renderer <DFF> @@ -489,11 +489,12 @@ $result = this.rowRenderer(item, itemIndex); } else { - $result = $("<tr>").addClass(this._getRowClasses(item, itemIndex)); + $result = $("<tr>"); this._renderCells($result, item); } - $result.data(JSGRID_ROW_DATA_KEY, item) + $result.addClass(this._getRowClasses(item, itemIndex)) + .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item,
3
Core: Add css classes to row rendered with custom renderer
2
.js
core
mit
tabalinas/jsgrid
10066003
<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) $result = this.rowRenderer(item, itemIndex); } else { $result = $("<tr>").addClass(this._getRowClasses(item, itemIndex)); this._renderCells($result, item); } $result.data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item, .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) { this.rowClick({ item: item, itemIndex: itemIndex, event: e }); }, this)) .on("dblclick", $.proxy(function(e) { this.rowDoubleClick({ item: item, 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> Core: Add css classes to row rendered with custom renderer <DFF> @@ -489,11 +489,12 @@ $result = this.rowRenderer(item, itemIndex); } else { - $result = $("<tr>").addClass(this._getRowClasses(item, itemIndex)); + $result = $("<tr>"); this._renderCells($result, item); } - $result.data(JSGRID_ROW_DATA_KEY, item) + $result.addClass(this._getRowClasses(item, itemIndex)) + .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item,
3
Core: Add css classes to row rendered with custom renderer
2
.js
core
mit
tabalinas/jsgrid
10066004
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066005
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066006
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066007
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066008
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066009
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066010
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066011
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066012
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066013
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066014
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066015
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066016
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066017
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066018
<NME> VisualLine.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.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a visual line in the document. /// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if /// all but the first are collapsed. /// </summary> public sealed class VisualLine { public const int LENGTH_LIMIT = 3000; private enum LifetimePhase : byte { Generating, Transforming, Live, Disposed } private readonly TextView _textView; private List<VisualLineElement> _elements; internal bool HasInlineObjects; private LifetimePhase _phase; /// <summary> /// Gets the document to which this VisualLine belongs. /// </summary> public TextDocument Document { get; } /// <summary> /// Gets the first document line displayed by this visual line. /// </summary> public DocumentLine FirstDocumentLine { get; } /// <summary> /// Gets the last document line displayed by this visual line. /// </summary> public DocumentLine LastDocumentLine { get; private set; } /// <summary> /// Gets a read-only collection of line elements. /// </summary> public ReadOnlyCollection<VisualLineElement> Elements { get; private set; } private ReadOnlyCollection<TextLine> _textLines; /// <summary> /// Gets a read-only collection of text lines. /// </summary> public ReadOnlyCollection<TextLine> TextLines { get { if (_phase < LifetimePhase.Live) throw new InvalidOperationException(); return _textLines; } } /// <summary> /// Gets the start offset of the VisualLine inside the document. /// This is equivalent to <c>FirstDocumentLine.Offset</c>. /// </summary> public int StartOffset => FirstDocumentLine.Offset; /// <summary> /// Length in visual line coordinates. /// </summary> public int VisualLength { get; private set; } /// <summary> /// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled. /// </summary> public int VisualLengthWithEndOfLineMarker { get { var length = VisualLength; if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++; return length; } } /// <summary> /// Gets the height of the visual line in device-independent pixels. /// </summary> public double Height { get; private set; } /// <summary> /// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document. /// </summary> public double VisualTop { get; internal set; } internal VisualLine(TextView textView, DocumentLine firstDocumentLine) { Debug.Assert(textView != null); Debug.Assert(firstDocumentLine != null); _textView = textView; Document = textView.Document; FirstDocumentLine = firstDocumentLine; } internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators) { Debug.Assert(_phase == LifetimePhase.Generating); foreach (var g in generators) { g.StartGeneration(context); } _elements = new List<VisualLineElement>(); PerformVisualElementConstruction(generators); foreach (var g in generators) { g.FinishGeneration(); } var globalTextRunProperties = context.GlobalTextRunProperties; foreach (var element in _elements) { element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); } this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); CalculateOffsets(); _phase = LifetimePhase.Transforming; } void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; var currentLineEnd = offset + lineLength; LastDocumentLine = FirstDocumentLine; var askInterestOffset = 0; // 0 or 1 while (offset + askInterestOffset <= currentLineEnd) { var textPieceEndOffset = currentLineEnd; foreach (var g in generators) { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); if (g.CachedInterest != -1) { if (g.CachedInterest < offset) throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", g.CachedInterest, "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); if (g.CachedInterest < textPieceEndOffset) textPieceEndOffset = g.CachedInterest; } } Debug.Assert(textPieceEndOffset >= offset); if (textPieceEndOffset > offset) { var textPieceLength = textPieceEndOffset - offset; _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; } // If no elements constructed / only zero-length elements constructed: // do not asking the generators again for the same location (would cause endless loop) askInterestOffset = 1; foreach (var g in generators) { if (g.CachedInterest == offset) { var element = g.ConstructElement(offset); if (element != null) { _elements.Add(element); if (element.DocumentLength > 0) { // a non-zero-length element was constructed askInterestOffset = 0; offset += element.DocumentLength; if (offset > currentLineEnd) { var newEndLine = Document.GetLineByOffset(offset); currentLineEnd = newEndLine.Offset + newEndLine.Length; this.LastDocumentLine = newEndLine; if (currentLineEnd < offset) { throw new InvalidOperationException( "The VisualLineElementGenerator " + g.GetType().Name + " produced an element which ends within the line delimiter"); } } break; } } } } } } private void CalculateOffsets() { var visualOffset = 0; var textOffset = 0; foreach (var element in _elements) { element.VisualColumn = visualOffset; element.RelativeTextOffset = textOffset; visualOffset += element.VisualLength; textOffset += element.DocumentLength; } VisualLength = visualOffset; Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset); } internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers) { Debug.Assert(_phase == LifetimePhase.Transforming); foreach (var transformer in transformers) { transformer.Transform(context, _elements); } _phase = LifetimePhase.Live; } /// <summary> /// Replaces the single element at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements) { ReplaceElement(elementIndex, 1, newElements); } /// <summary> /// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements. /// The replacement operation must preserve the document length, but may change the visual length. /// </summary> /// <remarks> /// This method may only be called by line transformers. /// </remarks> public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements) { if (_phase != LifetimePhase.Transforming) throw new InvalidOperationException("This method may only be called by line transformers."); var oldDocumentLength = 0; for (var i = elementIndex; i < elementIndex + count; i++) { oldDocumentLength += _elements[i].DocumentLength; } var newDocumentLength = 0; foreach (var newElement in newElements) { newDocumentLength += newElement.DocumentLength; } if (oldDocumentLength != newDocumentLength) throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength); _elements.RemoveRange(elementIndex, count); _elements.InsertRange(elementIndex, newElements); CalculateOffsets(); } internal void SetTextLines(List<TextLine> textLines) { _textLines = new ReadOnlyCollection<TextLine>(textLines); Height = 0; foreach (var line in textLines) Height += line.Height; } /// <summary> /// Gets the visual column from a document offset relative to the first line start. /// </summary> public int GetVisualColumn(int relativeTextOffset) { ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset"); foreach (var element in _elements) { if (element.RelativeTextOffset <= relativeTextOffset && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset) { return element.GetVisualColumn(relativeTextOffset); } } return VisualLength; } /// <summary> /// Gets the document offset (relative to the first line start) from a visual column. /// </summary> public int GetRelativeOffset(int visualColumn) { ThrowUtil.CheckNotNegative(visualColumn, "visualColumn"); var documentLength = 0; foreach (var element in _elements) { if (element.VisualColumn <= visualColumn && element.VisualColumn + element.VisualLength > visualColumn) { return element.GetRelativeOffset(visualColumn); } documentLength += element.DocumentLength; } return documentLength; } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn) { return GetTextLine(visualColumn, false); } /// <summary> /// Gets the text line containing the specified visual column. /// </summary> public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine) { if (visualColumn < 0) throw new ArgumentOutOfRangeException(nameof(visualColumn)); if (visualColumn >= VisualLengthWithEndOfLineMarker) return TextLines[TextLines.Count - 1]; foreach (var line in TextLines) { if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length) return line; visualColumn -= line.Length; } throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)"); } /// <summary> /// Gets the visual top from the specified text line. /// </summary> /// <returns>Distance in device-independent pixels /// from the top of the document to the top of the specified text line.</returns> public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var pos = VisualTop; foreach (var tl in TextLines) { if (tl == textLine) { switch (yPositionMode) { case VisualYPosition.LineTop: return pos; case VisualYPosition.LineMiddle: return pos + tl.Height / 2; case VisualYPosition.LineBottom: return pos + tl.Height; case VisualYPosition.TextTop: return pos + tl.Baseline - _textView.DefaultBaseline; case VisualYPosition.TextBottom: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight; case VisualYPosition.TextMiddle: return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2; case VisualYPosition.Baseline: return pos + tl.Baseline; default: throw new ArgumentException("Invalid yPositionMode:" + yPositionMode); } } pos += tl.Height; } throw new ArgumentException("textLine is not a line in this VisualLine"); } /// <summary> /// Gets the start visual column from the specified text line. /// </summary> public int GetTextLineVisualStartColumn(TextLine textLine) { if (!TextLines.Contains(textLine)) throw new ArgumentException("textLine is not a line in this VisualLine"); return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length); } /// <summary> /// Gets a TextLine by the visual position. /// </summary> public TextLine GetTextLineByVisualYPosition(double visualTop) { const double epsilon = 0.0001; var pos = VisualTop; foreach (var tl in TextLines) { pos += tl.Height; if (visualTop + epsilon < pos) return tl; } return TextLines[TextLines.Count - 1]; } /// <summary> /// Gets the visual position from the specified visualColumn. /// </summary> /// <returns>Position in device-independent pixels /// relative to the top left of the document.</returns> public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode) { var textLine = GetTextLine(visualColumn, isAtEndOfLine); var xPos = GetTextLineVisualXPosition(textLine, visualColumn); var yPos = GetTextLineVisualYPosition(textLine, yPositionMode); return new Point(xPos, yPos); } /// <summary> /// Gets the distance to the left border of the text area of the specified visual column. /// The visual column must belong to the specified text line. /// </summary> public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn) { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } return xPos; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point) { return GetVisualColumn(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(Point point, bool allowVirtualSpace) { return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace); } internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace); isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length); return vc; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, rounds to the nearest column. /// </summary> public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace) { if (xPos > textLine.WidthIncludingTrailingWhitespace) { if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero); return VisualLengthWithEndOfLineMarker + virtualX; } } var ch = textLine.GetCharacterHitFromDistance(xPos); return ch.FirstCharacterIndex + ch.TrailingLength; } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace) { return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace); } /// <summary> /// Validates the visual column and returns the correct one. /// </summary> public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace) { var firstDocumentLineOffset = FirstDocumentLine.Offset; if (visualColumn < 0) { return GetVisualColumn(offset - firstDocumentLineOffset); } var offsetFromVisualColumn = GetRelativeOffset(visualColumn); offsetFromVisualColumn += firstDocumentLineOffset; if (offsetFromVisualColumn != offset) { return GetVisualColumn(offset - firstDocumentLineOffset); } if (visualColumn > VisualLength && !allowVirtualSpace) { return VisualLength; } return visualColumn; } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point) { return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace); } /// <summary> /// Gets the visual column from a document position (relative to top left of the document). /// If the user clicks between two visual columns, returns the first of those columns. /// </summary> public int GetVisualColumnFloor(Point point, bool allowVirtualSpace) { return GetVisualColumnFloor(point, allowVirtualSpace, out _); } internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine) { var textLine = GetTextLineByVisualYPosition(point.Y); if (point.X > textLine.WidthIncludingTrailingWhitespace) { isAtEndOfLine = true; if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) { // clicking virtual space in the last line var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth); return VisualLengthWithEndOfLineMarker + virtualX; } // GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line // and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case // specially and return the line's end column instead. return GetTextLineVisualStartColumn(textLine) + textLine.Length; } isAtEndOfLine = false; var ch = textLine.GetCharacterHitFromDistance(point.X); return ch.FirstCharacterIndex; } /// <summary> /// Gets the text view position from the specified visual column. /// </summary> public TextViewPosition GetTextViewPosition(int visualColumn) { var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn); } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <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> /// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param> public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace) { var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine); var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset; var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; return pos; } /// <summary> /// Gets whether the visual line was disposed. /// </summary> public bool IsDisposed => _phase == LifetimePhase.Disposed; internal void Dispose() { if (_phase == LifetimePhase.Disposed) { return; } Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; if (_visual != null) { ((ISetLogicalParent)_visual).SetParent(null); } } _visual = null; _textLines = null; } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position. allowVirtualSpace = false; if (_elements.Count == 0) { // special handling for empty visual lines: if (allowVirtualSpace) { if (direction == LogicalDirection.Forward) return Math.Max(0, visualColumn + 1); if (visualColumn > 0) return visualColumn - 1; return -1; } // even though we don't have any elements, // there's a single caret stop at visualColumn 0 if (visualColumn < 0 && direction == LogicalDirection.Forward) return 0; if (visualColumn > 0 && direction == LogicalDirection.Backward) return 0; return -1; } int i; if (direction == LogicalDirection.Backward) { // Search Backwards: // If the last element doesn't handle line borders, return the line end as caret stop if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd()) { if (allowVirtualSpace) return visualColumn - 1; return VisualLength; } // skip elements that start after or at visualColumn for (i = _elements.Count - 1; i >= 0; i--) { if (_elements[i].VisualColumn < visualColumn) break; } // search last element that has a caret stop for (; i >= 0; i--) { var pos = _elements[i].GetNextCaretPosition( Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1), direction, mode); if (pos >= 0) return pos; } // If we've found nothing, and the first element doesn't handle line borders, // return the line start as normal caret stop. if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; } else { // Search Forwards: // If the first element doesn't handle line borders, return the line start as caret stop if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode)) return 0; // skip elements that end before or at visualColumn for (i = 0; i < _elements.Count; i++) { if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn) break; } // search first element that has a caret stop for (; i < _elements.Count; i++) { var pos = _elements[i].GetNextCaretPosition( Math.Max(visualColumn, _elements[i].VisualColumn - 1), direction, mode); if (pos >= 0) return pos; } // if we've found nothing, and the last element doesn't handle line borders, // return the line end as caret stop if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd()) { if (visualColumn < VisualLength) return VisualLength; if (allowVirtualSpace) return visualColumn + 1; } } // we've found nothing, return -1 and let the caret search continue in the next line return -1; } private static bool HasStopsInVirtualSpace(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode) { return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint; } private static bool HasImplicitStopAtLineEnd() => true; private VisualLineDrawingVisual _visual; internal VisualLineDrawingVisual Render() { Debug.Assert(_phase == LifetimePhase.Live); if (_visual == null) { _visual = new VisualLineDrawingVisual(this); ((ISetLogicalParent)_visual).SetParent(_textView); } return _visual; } } // TODO: can inherit from Layoutable, but dev tools crash internal sealed class VisualLineDrawingVisual : Control { public VisualLine VisualLine { get; } public double LineHeight { get; } internal bool IsAdded { get; set; } public VisualLineDrawingVisual(VisualLine visualLine) { VisualLine = visualLine; LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height); } public override void Render(DrawingContext context) { double pos = 0; foreach (var textLine in VisualLine.TextLines) { textLine.Draw(context, new Point(0, pos)); pos += textLine.Height; } } } } <MSG> Merge pull request #269 from AvaloniaUI/reformat-visual-line Reformat code <DFF> @@ -21,13 +21,16 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; + using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Media.TextFormatting; + using AvaloniaEdit.Document; using AvaloniaEdit.Utils; + using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering @@ -146,73 +149,84 @@ namespace AvaloniaEdit.Rendering g.FinishGeneration(); } - var globalTextRunProperties = context.GlobalTextRunProperties; - foreach (var element in _elements) { - element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); - } - this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); - CalculateOffsets(); - _phase = LifetimePhase.Transforming; - } - - void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) - { + var globalTextRunProperties = context.GlobalTextRunProperties; + foreach (var element in _elements) + { + element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties)); + } + this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements); + CalculateOffsets(); + _phase = LifetimePhase.Transforming; + } + + void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators) + { var lineLength = FirstDocumentLine.Length; var offset = FirstDocumentLine.Offset; - var currentLineEnd = offset + lineLength; - LastDocumentLine = FirstDocumentLine; - var askInterestOffset = 0; // 0 or 1 - - while (offset + askInterestOffset <= currentLineEnd) { - var textPieceEndOffset = currentLineEnd; - foreach (var g in generators) { + var currentLineEnd = offset + lineLength; + LastDocumentLine = FirstDocumentLine; + var askInterestOffset = 0; // 0 or 1 + + while (offset + askInterestOffset <= currentLineEnd) + { + var textPieceEndOffset = currentLineEnd; + foreach (var g in generators) + { g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset); - if (g.CachedInterest != -1) { - if (g.CachedInterest < offset) - throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", - g.CachedInterest, - "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); - if (g.CachedInterest < textPieceEndOffset) - textPieceEndOffset = g.CachedInterest; - } - } - Debug.Assert(textPieceEndOffset >= offset); - if (textPieceEndOffset > offset) { - var textPieceLength = textPieceEndOffset - offset; - + if (g.CachedInterest != -1) + { + if (g.CachedInterest < offset) + throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset", + g.CachedInterest, + "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest."); + if (g.CachedInterest < textPieceEndOffset) + textPieceEndOffset = g.CachedInterest; + } + } + Debug.Assert(textPieceEndOffset >= offset); + if (textPieceEndOffset > offset) + { + var textPieceLength = textPieceEndOffset - offset; + _elements.Add(new VisualLineText(this, textPieceLength)); offset = textPieceEndOffset; - } - // If no elements constructed / only zero-length elements constructed: - // do not asking the generators again for the same location (would cause endless loop) - askInterestOffset = 1; - foreach (var g in generators) { - if (g.CachedInterest == offset) { - var element = g.ConstructElement(offset); - if (element != null) { - _elements.Add(element); - if (element.DocumentLength > 0) { - // a non-zero-length element was constructed - askInterestOffset = 0; - offset += element.DocumentLength; - if (offset > currentLineEnd) { - var newEndLine = Document.GetLineByOffset(offset); - currentLineEnd = newEndLine.Offset + newEndLine.Length; - this.LastDocumentLine = newEndLine; - if (currentLineEnd < offset) { - throw new InvalidOperationException( - "The VisualLineElementGenerator " + g.GetType().Name + - " produced an element which ends within the line delimiter"); - } - } - break; - } - } - } - } - } - } + } + // If no elements constructed / only zero-length elements constructed: + // do not asking the generators again for the same location (would cause endless loop) + askInterestOffset = 1; + foreach (var g in generators) + { + if (g.CachedInterest == offset) + { + var element = g.ConstructElement(offset); + if (element != null) + { + _elements.Add(element); + if (element.DocumentLength > 0) + { + // a non-zero-length element was constructed + askInterestOffset = 0; + offset += element.DocumentLength; + if (offset > currentLineEnd) + { + var newEndLine = Document.GetLineByOffset(offset); + currentLineEnd = newEndLine.Offset + newEndLine.Length; + this.LastDocumentLine = newEndLine; + if (currentLineEnd < offset) + { + throw new InvalidOperationException( + "The VisualLineElementGenerator " + g.GetType().Name + + " produced an element which ends within the line delimiter"); + } + } + break; + } + } + } + } + } + } private void CalculateOffsets() { @@ -445,15 +459,15 @@ namespace AvaloniaEdit.Rendering { if (textLine == null) throw new ArgumentNullException(nameof(textLine)); - + var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker))); - + if (visualColumn > VisualLengthWithEndOfLineMarker) { xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth; } - + return xPos; } @@ -499,7 +513,7 @@ namespace AvaloniaEdit.Rendering } var ch = textLine.GetCharacterHitFromDistance(xPos); - + return ch.FirstCharacterIndex + ch.TrailingLength; } @@ -572,9 +586,9 @@ namespace AvaloniaEdit.Rendering } isAtEndOfLine = false; - + var ch = textLine.GetCharacterHitFromDistance(point.X); - + return ch.FirstCharacterIndex; } @@ -634,7 +648,7 @@ namespace AvaloniaEdit.Rendering { return; } - + Debug.Assert(_phase == LifetimePhase.Live); _phase = LifetimePhase.Disposed; @@ -647,7 +661,7 @@ namespace AvaloniaEdit.Rendering _visual = null; _textLines = null; - } + } /// <summary> /// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
83
Merge pull request #269 from AvaloniaUI/reformat-visual-line
69
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066019
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066020
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066021
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066022
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066023
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066024
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066025
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066026
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066027
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066028
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066029
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066030
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066031
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066032
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066033
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update deps <DFF> @@ -2,7 +2,7 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.999-cibuild0020463-beta</AvaloniaVersion> + <AvaloniaVersion>0.10.999-cibuild0020651-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version>
1
Update deps
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10066034
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length, 1, "row element is provided in updating event args"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row.length, 1, "row element is provided in updated event args"); gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Pass previousItem to onItemUpdating and onItemUpdated callbacks <DFF> @@ -1061,6 +1061,7 @@ $(function() { grid.fields[0].editControl.val("new value"); grid.updateItem(); + deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length,
2
Core: Pass previousItem to onItemUpdating and onItemUpdated callbacks
0
.js
tests
mit
tabalinas/jsgrid
10066035
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length, 1, "row element is provided in updating event args"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row.length, 1, "row element is provided in updated event args"); gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Pass previousItem to onItemUpdating and onItemUpdated callbacks <DFF> @@ -1061,6 +1061,7 @@ $(function() { grid.fields[0].editControl.val("new value"); grid.updateItem(); + deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length,
2
Core: Pass previousItem to onItemUpdating and onItemUpdated callbacks
0
.js
tests
mit
tabalinas/jsgrid
10066036
<NME> README.md <BEF> # FruitMachine [![Build Status](https://api.travis-ci.com/ftlabs/fruitmachine.svg)](https://travis-ci.com/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/ftlabs/fruitmachine/badge.png)](https://coveralls.io/r/ftlabs/fruitmachine) A lightweight component layout engine for client and server. FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/). ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create a module var apple = new Apple(); // Render & inject into DOM apple.render().inject(document.body); 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> Updated docs <DFF> @@ -15,7 +15,9 @@ var Apple = FruitMachine.define({ var apple = new Apple(); // Render & inject into DOM -apple.render().inject(document.body); +apple + .render() + .inject(document.body); apple.el.outerHTML; //=> <div class="apple">hello</div>
3
Updated docs
1
.md
md
mit
ftlabs/fruitmachine
10066037
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); done(); } }); }); it('should bypass insertion if before returns `false`', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2'); }, 1000); }); }); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // verify image was loaded if (img.src === src) assert.equal(img.naturalWidth > 0, true); }); } function assertNotLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // fail if image was loaded if (img.src === src) assert.equal(img.naturalWidth, 0); }); } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('detects png|gif|jpg|svg|webp extensions', function(done) { let files = [ 'assets/flash.png', 'assets/flash.gif', 'assets/flash.jpg', 'assets/flash.svg', 'assets/flash.webp' ]; loadjs(files, function() { files.forEach(file => {assertLoaded(file);}); done(); }); }); it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with anchor tags', function(done) { var src = 'assets/flash.png#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); it('should support mix of img and js', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src, 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> Adding support for detecting beforeload-blocked scripts <DFF> @@ -183,4 +183,23 @@ describe('LoadJS tests', function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2'); }, 1000); }); + + // Un-'x' this for testing ad blocked scripts. + // Ghostery: Disallow "Google Adservices" + // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a custom filter under Options + // + xit('it should report ad blocked scripts as missing', function(done) { + var blockedScript = 'https://www.googletagservices.com/tag/js/gpt.js'; + + loadjs([blockedScript, 'assets/file1.js'], + function() { + throw "Executed success callback"; + }, + function(pathsNotFound) { + assert.equal(pathsLoaded['file1.js'], true); + assert.equal(pathsNotFound.length, 1); + assert.equal(pathsNotFound[0], blockedScript); + done(); + }); + }); });
19
Adding support for detecting beforeload-blocked scripts
0
.js
js
mit
muicss/loadjs
10066038
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); done(); } }); }); it('should bypass insertion if before returns `false`', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2'); }, 1000); }); }); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // verify image was loaded if (img.src === src) assert.equal(img.naturalWidth > 0, true); }); } function assertNotLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // fail if image was loaded if (img.src === src) assert.equal(img.naturalWidth, 0); }); } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('detects png|gif|jpg|svg|webp extensions', function(done) { let files = [ 'assets/flash.png', 'assets/flash.gif', 'assets/flash.jpg', 'assets/flash.svg', 'assets/flash.webp' ]; loadjs(files, function() { files.forEach(file => {assertLoaded(file);}); done(); }); }); it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with anchor tags', function(done) { var src = 'assets/flash.png#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); it('should support mix of img and js', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src, 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> Adding support for detecting beforeload-blocked scripts <DFF> @@ -183,4 +183,23 @@ describe('LoadJS tests', function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle2'); }, 1000); }); + + // Un-'x' this for testing ad blocked scripts. + // Ghostery: Disallow "Google Adservices" + // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a custom filter under Options + // + xit('it should report ad blocked scripts as missing', function(done) { + var blockedScript = 'https://www.googletagservices.com/tag/js/gpt.js'; + + loadjs([blockedScript, 'assets/file1.js'], + function() { + throw "Executed success callback"; + }, + function(pathsNotFound) { + assert.equal(pathsLoaded['file1.js'], true); + assert.equal(pathsNotFound.length, 1); + assert.equal(pathsNotFound[0], blockedScript); + done(); + }); + }); });
19
Adding support for detecting beforeload-blocked scripts
0
.js
js
mit
muicss/loadjs
10066039
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066040
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066041
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066042
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066043
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066044
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066045
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066046
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066047
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066048
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit
10066049
<NME> UnitTestApplication.cs <BEF> using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reflection; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Styling; using Avalonia.Threading; namespace AvaloniaEdit.AvaloniaMocks { public class UnitTestApplication : Application { public UnitTestApplication(TestServices services) { Services = services ?? new TestServices(); RegisterServices(); } public TestServices Services { get; } public static IDisposable Start(TestServices services = null) { AvaloniaLocator.Current = (AvaloniaLocator.CurrentMutable = new AvaloniaLocator()); var app = new UnitTestApplication(services); AvaloniaLocator.CurrentMutable.BindToSelf<Application>(app); var updateServices = Dispatcher.UIThread.GetType().GetMethod("UpdateServices", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); updateServices?.Invoke(Dispatcher.UIThread, null); return Disposable.Create(() => { updateServices?.Invoke(Dispatcher.UIThread, null); AvaloniaLocator.CurrentMutable = null; AvaloniaLocator.Current = null; }); } public override void RegisterServices() { AvaloniaLocator.CurrentMutable .Bind<IAssetLoader>().ToConstant(Services.AssetLoader) .Bind<IFocusManager>().ToConstant(Services.FocusManager) .BindToSelf<IGlobalStyles>(this) .Bind<IInputManager>().ToConstant(Services.InputManager) .Bind<IKeyboardDevice>().ToConstant(Services.KeyboardDevice?.Invoke()) .Bind<IKeyboardNavigationHandler>().ToConstant(Services.KeyboardNavigation) .Bind<ILayoutManager>().ToConstant(Services.LayoutManager) .Bind<IMouseDevice>().ToConstant(Services.MouseDevice?.Invoke()) .Bind<IRuntimePlatform>().ToConstant(Services.Platform) .Bind<IPlatformRenderInterface>().ToConstant(Services.RenderInterface) .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) .Bind<IApplicationLifecycle>().ToConstant(this); var styles = Services.Theme?.Invoke(); if (styles != null) .Bind<ITextShaperImpl>().ToConstant(Services.TextShaperImpl); //var styles = Services.Theme?.Invoke(); //if (styles != null) //{ // Styles.AddRange(styles); //} } } } <MSG> Merge pull request #90 from jp2masa/update-avalonia Updated Avalonia <DFF> @@ -54,8 +54,7 @@ namespace AvaloniaEdit.AvaloniaMocks .Bind<IScheduler>().ToConstant(Services.Scheduler) .Bind<IStandardCursorFactory>().ToConstant(Services.StandardCursorFactory) .Bind<IStyler>().ToConstant(Services.Styler) - .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform) - .Bind<IApplicationLifecycle>().ToConstant(this); + .Bind<IWindowingPlatform>().ToConstant(Services.WindowingPlatform); var styles = Services.Theme?.Invoke(); if (styles != null)
1
Merge pull request #90 from jp2masa/update-avalonia
2
.cs
Tests/AvaloniaMocks/UnitTestApplication
mit
AvaloniaUI/AvaloniaEdit