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
10061550
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </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> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <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 to avalonia release candidate. <DFF> @@ -9,7 +9,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </ItemGroup>
1
update to avalonia release candidate.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10061551
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </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> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <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 to avalonia release candidate. <DFF> @@ -9,7 +9,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </ItemGroup>
1
update to avalonia release candidate.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10061552
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </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> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <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 to avalonia release candidate. <DFF> @@ -9,7 +9,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </ItemGroup>
1
update to avalonia release candidate.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10061553
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </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> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <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 to avalonia release candidate. <DFF> @@ -9,7 +9,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </ItemGroup>
1
update to avalonia release candidate.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10061554
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </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> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <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 to avalonia release candidate. <DFF> @@ -9,7 +9,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </ItemGroup>
1
update to avalonia release candidate.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10061555
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </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> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <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 to avalonia release candidate. <DFF> @@ -9,7 +9,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Avalonia" Version="0.5.2-build4525-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" /> <PackageReference Include="System.Collections.Immutable" Version="1.4.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> </ItemGroup>
1
update to avalonia release candidate.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10061556
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061557
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061558
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061559
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061560
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061561
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061562
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061563
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061564
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061565
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061566
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061567
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061568
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061569
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061570
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { } UpdateSnapshot(); InvalidateLine(startLine); } catch (Exception ex) if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Invalidate current and previous line some grammars (JSON, csharp, ...), need to invalidate previous lines. Otherwise some tokens are not revalidate properly. Examples: - press enter after the class bracket in a csharp file. - press enter to add a new property to a JSON fiie. <DFF> @@ -171,6 +171,12 @@ namespace AvaloniaEdit.TextMate } UpdateSnapshot(); + + // invalidate current and previous line + // some grammars (JSON, csharp, ...) + // need to invalidate previous lines + if (startLine - 1 >= 0) + InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex)
6
Invalidate current and previous line
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061571
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061572
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061573
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061574
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061575
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061576
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061577
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061578
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061579
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061580
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061581
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061582
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061583
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061584
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061585
<NME> SearchCommands.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 Avalonia.Input; using Avalonia.Threading; using AvaloniaEdit.Editing; namespace AvaloniaEdit.Search { /// <summary> /// Search commands for AvalonEdit. /// </summary> public static class SearchCommands { /// <summary> /// Finds the next occurrence in the file. /// </summary> public static readonly RoutedCommand FindNext = new RoutedCommand(nameof(FindNext), new KeyGesture(Key.F3)); /// <summary> /// Finds the previous occurrence in the file. /// </summary> public static readonly RoutedCommand FindPrevious = new RoutedCommand(nameof(FindPrevious), new KeyGesture(Key.F3, KeyModifiers.Shift)); /// <summary> /// Closes the SearchPanel. /// </summary> public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(nameof(CloseSearchPanel), new KeyGesture(Key.Escape)); /// <summary> /// Replaces the next occurrence in the document. /// </summary> public static readonly RoutedCommand ReplaceNext = new RoutedCommand(nameof(ReplaceNext), new KeyGesture(Key.R, KeyModifiers.Alt)); /// <summary> /// Replaces all the occurrences in the document. /// </summary> public static readonly RoutedCommand ReplaceAll = new RoutedCommand(nameof(ReplaceAll), new KeyGesture(Key.A, KeyModifiers.Alt)); } /// <summary> /// TextAreaInputHandler that registers all search-related commands. /// </summary> internal class SearchInputHandler : TextAreaInputHandler { public SearchInputHandler(TextArea textArea, SearchPanel panel) : base(textArea) { RegisterCommands(CommandBindings); _panel = panel; } internal void RegisterGlobalCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); } private void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { commandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, ExecuteFind)); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, ExecuteReplace)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, ExecuteReplaceNext, CanExecuteWithOpenSearchPanel)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, ExecuteReplaceAll, CanExecuteWithOpenSearchPanel)); commandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel)); } private readonly SearchPanel _panel; private void ExecuteFind(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: false); } private void ExecuteReplace(object sender, ExecutedRoutedEventArgs e) { FindOrReplace(isReplaceMode: true); } private void FindOrReplace(bool isReplaceMode) { _panel.IsReplaceMode = isReplaceMode; _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e) { if (_panel.IsClosed) { e.CanExecute = false; // Continue routing so that the key gesture can be consumed by another component. //e.ContinueRouting = true; } else { e.CanExecute = true; e.Handled = true; } } private void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindNext(); e.Handled = true; } } private void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.FindPrevious(); e.Handled = true; } } private void ExecuteReplaceNext(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceNext(); e.Handled = true; } } private void ExecuteReplaceAll(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.ReplaceAll(); e.Handled = true; } } private void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e) { if (!_panel.IsClosed) { _panel.Close(); e.Handled = true; } } /// <summary> /// Fired when SearchOptions are modified inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged { add => _panel.SearchOptionsChanged += value; remove => _panel.SearchOptionsChanged -= value; } } } <MSG> Merge pull request #65 from AvaloniaUI/fixes/update-avalonia Fixes/update avalonia <DFF> @@ -104,7 +104,7 @@ namespace AvaloniaEdit.Search _panel.Open(); if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline)) _panel.SearchPattern = TextArea.Selection.GetText(); - Dispatcher.UIThread.InvokeAsync(_panel.Reactivate, DispatcherPriority.Input); + Dispatcher.UIThread.Post(_panel.Reactivate, DispatcherPriority.Input); } private void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
1
Merge pull request #65 from AvaloniaUI/fixes/update-avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061586
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061587
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061588
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061589
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061590
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061591
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061592
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061593
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061594
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061595
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061596
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061597
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061598
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061599
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061600
<NME> CaretNavigationCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Media.TextFormatting; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Editing { internal enum CaretMovementType { None, CharLeft, CharRight, Backspace, WordLeft, WordRight, LineUp, LineDown, PageUp, PageDown, LineStart, LineEnd, DocumentStart, DocumentEnd } internal static class CaretNavigationCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler) { AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture)); } static CaretNavigationCommandHandler() { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp)); AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp)); AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart)); AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument) AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument) AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd)); foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection) AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.Caret.Offset = textArea.Document.TextLength; textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength); } } private static TextArea GetTextArea(object target) { return target as TextArea; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; textArea.ClearSelection(); MoveCaret(textArea, direction); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.Handled = true; // First, convert the selection into a rectangle selection // (this is required so that virtual space gets enabled for the caret movement) if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) { textArea.Selection = textArea.Selection.IsEmpty ? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position) : new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position); } // Now move the caret and extend the selection var oldPosition = textArea.Caret.Position; MoveCaret(textArea, direction); textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position); textArea.Caret.BringCaretToView(); } }; } #region Caret movement internal static void MoveCaret(TextArea textArea, CaretMovementType direction) { var desiredXPos = textArea.Caret.DesiredXPos; textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos); textArea.Caret.DesiredXPos = desiredXPos; } internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos) { switch (direction) { case CaretMovementType.None: return caretPosition; case CaretMovementType.DocumentStart: desiredXPos = double.NaN; return new TextViewPosition(0, 0); case CaretMovementType.DocumentEnd: desiredXPos = double.NaN; return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } var caretLine = textView.Document.GetLineByNumber(caretPosition.Line); var visualLine = textView.GetOrConstructVisualLine(caretLine); var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine); switch (direction) { case CaretMovementType.CharLeft: desiredXPos = double.NaN; // do not move caret to previous line in virtual space if (caretPosition.VisualColumn == 0 && enableVirtualSpace) return caretPosition; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.Backspace: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace); case CaretMovementType.CharRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace); case CaretMovementType.WordLeft: desiredXPos = double.NaN; return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.WordRight: desiredXPos = double.NaN; return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace); case CaretMovementType.LineUp: case CaretMovementType.LineDown: case CaretMovementType.PageUp: case CaretMovementType.PageDown: return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos); case CaretMovementType.LineStart: desiredXPos = double.NaN; return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace); case CaretMovementType.LineEnd: desiredXPos = double.NaN; return GetEndOfLineCaretPosition(visualLine, textLine); default: throw new NotSupportedException(direction.ToString()); } } #endregion #region Home/End private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine); if (newVisualCol == 0) newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace); if (newVisualCol < 0) throw ThrowUtil.NoValidCaretPosition(); // when the caret is already at the start of the text, jump to start before whitespace if (newVisualCol == oldVisualColumn) newVisualCol = 0; return visualLine.GetTextViewPosition(newVisualCol); } private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine) { var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength; var pos = visualLine.GetTextViewPosition(newVisualCol); pos.IsAtEndOfLine = true; return pos; } #endregion #region By-character / By-word movement private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to start of next line var nextDocumentLine = visualLine.LastDocumentLine.NextLine; if (nextDocumentLine != null) { var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine); pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return nextLine.GetTextViewPosition(pos); } else { // at end of document Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength); return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength)); } } } private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace) { var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos >= 0) { return visualLine.GetTextViewPosition(pos); } else { // move to end of previous line var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine; if (previousDocumentLine != null) { var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine); pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace); if (pos < 0) throw ThrowUtil.NoValidCaretPosition(); return previousLine.GetTextViewPosition(pos); } else { // at start of document Debug.Assert(visualLine.FirstDocumentLine.Offset == 0); return new TextViewPosition(0, 0); } } } #endregion #region Line+Page up/down private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos) { // moving up/down happens using the desired visual X position if (double.IsNaN(xPos)) xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn); // now find the TextLine+VisualLine where the caret will end up in var targetVisualLine = visualLine; TextLine targetLine; var textLineIndex = visualLine.TextLines.IndexOf(textLine); switch (direction) { case CaretMovementType.LineUp: { // Move up: move to the previous TextLine in the same visual line // or move to the last TextLine of the previous visual line var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1; if (textLineIndex > 0) { targetLine = visualLine.TextLines[textLineIndex - 1]; } else if (prevLineNumber >= 1) { var prevLine = textView.Document.GetLineByNumber(prevLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(prevLine); targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1]; } else { targetLine = null; } break; } case CaretMovementType.LineDown: { // Move down: move to the next TextLine in the same visual line // or move to the first TextLine of the next visual line var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1; if (textLineIndex < visualLine.TextLines.Count - 1) { targetLine = visualLine.TextLines[textLineIndex + 1]; } else if (nextLineNumber <= textView.Document.LineCount) { var nextLine = textView.Document.GetLineByNumber(nextLineNumber); targetVisualLine = textView.GetOrConstructVisualLine(nextLine); targetLine = targetVisualLine.TextLines[0]; } else { targetLine = null; } break; } case CaretMovementType.PageUp: case CaretMovementType.PageDown: { // Page up/down: find the target line using its visual position var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle); if (direction == CaretMovementType.PageUp) yPos -= textView.Bounds.Height; else yPos += textView.Bounds.Height; var newLine = textView.GetDocumentLineByVisualTop(yPos); targetVisualLine = textView.GetOrConstructVisualLine(newLine); targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos); break; } default: throw new NotSupportedException(direction.ToString()); } if (targetLine != null) { var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle); var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace); // prevent wrapping to the next line; TODO: could 'IsAtEnd' help here? var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine); if (newVisualColumn >= targetLineStartCol + targetLine.Length) { if (newVisualColumn <= targetVisualLine.VisualLength) newVisualColumn = targetLineStartCol + targetLine.Length - 1; } return targetVisualLine.GetTextViewPosition(newVisualColumn); } else { return caretPosition; } } #endregion } } <MSG> Merge pull request #81 from gurgendav/mac-shortcuts Fix editor shortcuts on mac replacing ctrl with cmd <DFF> @@ -62,9 +62,14 @@ namespace AvaloniaEdit.Editing static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); - private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); + } + + private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) + { + AddBinding(command, handler); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } @@ -108,7 +113,7 @@ namespace AvaloniaEdit.Editing AddBinding(EditingCommands.MoveToDocumentEnd, KeyModifiers.Control, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd)); AddBinding(EditingCommands.SelectToDocumentEnd, KeyModifiers.Control | KeyModifiers.Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd)); - AddBinding(ApplicationCommands.SelectAll, KeyModifiers.Control, Key.A, OnSelectAll); + AddBinding(ApplicationCommands.SelectAll, OnSelectAll); } private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
7
Merge pull request #81 from gurgendav/mac-shortcuts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061601
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061602
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061603
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061604
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061605
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061606
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061607
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061608
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061609
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061610
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061611
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061612
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061613
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061614
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061615
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU {4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU {03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU {9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU {63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631} EndGlobalSection EndGlobal <MSG> Remove unwanted changes in sln file <DFF> @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28621.142 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject
2
Remove unwanted changes in sln file
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10061616
<NME> .travis.yml <BEF> ADDFILE <MSG> Tests: Add travis.yml config <DFF> @@ -0,0 +1,1 @@ +language: node_js
1
Tests: Add travis.yml config
0
.yml
travis
mit
tabalinas/jsgrid
10061617
<NME> .travis.yml <BEF> ADDFILE <MSG> Tests: Add travis.yml config <DFF> @@ -0,0 +1,1 @@ +language: node_js
1
Tests: Add travis.yml config
0
.yml
travis
mit
tabalinas/jsgrid
10061618
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061619
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061620
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061621
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061622
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061623
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061624
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061625
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061626
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061627
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061628
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061629
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061630
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061631
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061632
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange(OffsetProperty); AffectsRender(OffsetProperty); } /// <summary> AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Obsolete fixes <DFF> @@ -62,8 +62,8 @@ namespace AvaloniaEdit.Editing DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); - AffectsArrange(OffsetProperty); - AffectsRender(OffsetProperty); + AffectsArrange<TextArea>(OffsetProperty); + AffectsRender<TextArea>(OffsetProperty); } /// <summary>
2
Obsolete fixes
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061633
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; } }, mixin: function(original) { // Loop over every argument after the first. slice.call(arguments, 1).forEach(function(source) { } // Mixin Events and extend the prototype mixin(View.prototype, Events, { // Empty methods you can overwrite // in your custom view logic. onTeardown: function() {}, onDestroy: function() {}, _configure: function(options) { this._id = options.id || util.uniqueId('auto_'); this._fmid = options.fmid || util.uniqueId('fmid'); <MSG> Added support for optional bubbling events <DFF> @@ -72,6 +72,10 @@ } }, + isArray: function(arg) { + return arg instanceof Array; + }, + mixin: function(original) { // Loop over every argument after the first. slice.call(arguments, 1).forEach(function(source) { @@ -298,7 +302,45 @@ } // Mixin Events and extend the prototype - mixin(View.prototype, Events, { + mixin(View.prototype, { + on: Events.on, + off: Events.off, + + /** + * Proxies the standard Event.trigger + * method so that we can add bubble + * functionality. + * + * Options: + * + * - `bubble` States whether the event + * should bubble through parent views. + * + * @param {String} key + * @param {Array} args + * @param {Object} options + * @return {View} + * @api public + */ + trigger: function(key, args, options) { + options = options || {}; + + // Allows options to be + // the second or third arg + if (!util.isArray(args)) { + options = args || {}; + args = []; + } + + // Trigger event + Events.trigger.apply(this, [key].concat(args)); + + // Trigger the same event on the parent view + if (options.bubble && this.parent) this.parent.trigger(key, args, options); + + // Allow chaining + return this; + }, // Empty methods you can overwrite // in your custom view logic. @@ -307,6 +349,14 @@ onTeardown: function() {}, onDestroy: function() {}, + /** + * Configures the new View + * with the options passed + * to the constructor. + * + * @param {Object} options + * @api private + */ _configure: function(options) { this._id = options.id || util.uniqueId('auto_'); this._fmid = options.fmid || util.uniqueId('fmid');
51
Added support for optional bubbling events
1
.js
js
mit
ftlabs/fruitmachine
10061634
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061635
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061636
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061637
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061638
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061639
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061640
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061641
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061642
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061643
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061644
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061645
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061646
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061647
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061648
<NME> SearchPanel.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.Linq; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Search { /// <summary> /// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea. /// </summary> public class SearchPanel : TemplatedControl, IRoutedCommandBindable { private TextArea _textArea; private SearchInputHandler _handler; private TextDocument _currentDocument; private SearchResultBackgroundRenderer _renderer; private TextBox _searchTextBox; private TextEditor _textEditor { get; set; } private Border _border; #region DependencyProperties /// <summary> /// Dependency property for <see cref="UseRegex"/>. /// </summary> public static readonly StyledProperty<bool> UseRegexProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex)); /// <summary> /// Gets/sets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get => GetValue(UseRegexProperty); set => SetValue(UseRegexProperty, value); } /// <summary> /// Dependency property for <see cref="MatchCase"/>. /// </summary> public static readonly StyledProperty<bool> MatchCaseProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase)); /// <summary> /// Gets/sets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get => GetValue(MatchCaseProperty); set => SetValue(MatchCaseProperty, value); } /// <summary> /// Dependency property for <see cref="WholeWords"/>. /// </summary> public static readonly StyledProperty<bool> WholeWordsProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords)); /// <summary> /// Gets/sets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get => GetValue(WholeWordsProperty); set => SetValue(WholeWordsProperty, value); } /// <summary> /// Dependency property for <see cref="SearchPattern"/>. /// </summary> public static readonly StyledProperty<string> SearchPatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), ""); /// <summary> /// Gets/sets the search pattern. set => SetValue(SearchPatternProperty, value); } public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode public static readonly StyledProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); set => SetValue(IsReplaceModeProperty, value); } public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern if (panel._textEditor == null || !v1) return v1; return !panel._textEditor.IsReadOnly; } public bool IsReplaceMode { get => GetValue(IsReplaceModeProperty); set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value); } public static readonly StyledProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern { get => GetValue(ReplacePatternProperty); set => SetValue(ReplacePatternProperty, value); } /// <summary> /// Dependency property for <see cref="MarkerBrush"/>. /// </summary> public static readonly StyledProperty<IBrush> MarkerBrushProperty = AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen); /// <summary> /// Gets/sets the Brush used for marking search results in the TextView. /// </summary> public IBrush MarkerBrush { get => GetValue(MarkerBrushProperty); set => SetValue(MarkerBrushProperty, value); } #endregion private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel._renderer.MarkerBrush = (IBrush)e.NewValue; } } private ISearchStrategy _strategy; private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is SearchPanel panel) { panel.ValidateSearchText(); panel.UpdateSearch(); } } private void UpdateSearch() { // only reset as long as there are results // if no results are found, the "no matches found" message should not flicker. // if results are found by the next run, the message will be hidden inside DoSearch ... if (_renderer.CurrentResults.Any()) _messageView.IsOpen = false; _strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal); OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords)); DoSearch(true); } static SearchPanel() { UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback); MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback); WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback); SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback); MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback); } /// <summary> /// Creates a new SearchPanel. /// </summary> private SearchPanel() { } /// <summary> /// Creates a SearchPanel and installs it to the TextEditor's TextArea. /// </summary> /// <remarks>This is a convenience wrapper.</remarks> public static SearchPanel Install(TextEditor editor) { if (editor == null) throw new ArgumentNullException(nameof(editor)); SearchPanel searchPanel = Install(editor.TextArea); searchPanel._textEditor = editor; return searchPanel; } /// <summary> /// Creates a SearchPanel and installs it to the TextArea. /// </summary> public static SearchPanel Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); var panel = new SearchPanel(); panel.AttachInternal(textArea); panel._handler = new SearchInputHandler(textArea, panel); textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler); ((ISetLogicalParent)panel).SetParent(textArea); return panel; } /// <summary> /// Adds the commands used by SearchPanel to the given CommandBindingCollection. /// </summary> public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings) { _handler.RegisterGlobalCommands(commandBindings); } /// <summary> /// Removes the SearchPanel from the TextArea. /// </summary> public void Uninstall() private void AttachInternal(TextArea textArea) { _textArea = textArea; this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; } private void AttachInternal(TextArea textArea) { _textArea = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; if (_currentDocument != null) _currentDocument.TextChanged += TextArea_Document_TextChanged; textArea.DocumentChanged += TextArea_DocumentChanged; KeyDown += SearchLayerKeyDown; CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious())); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close())); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) => { IsReplaceMode = false; Reactivate(); })); CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode)); CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode)); IsClosed = true; } private void TextArea_DocumentChanged(object sender, EventArgs e) { if (_currentDocument != null) _currentDocument.TextChanged -= TextArea_Document_TextChanged; _currentDocument = _textArea.Document; if (_currentDocument != null) { _currentDocument.TextChanged += TextArea_Document_TextChanged; DoSearch(false); } } private void TextArea_Document_TextChanged(object sender, EventArgs e) { DoSearch(false); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _border = e.NameScope.Find<Border>("PART_Border"); _searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox"); _messageView = e.NameScope.Find<Popup>("PART_MessageView"); _messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent"); } private void ValidateSearchText() { if (_searchTextBox == null) return; try { UpdateSearch(); _validationError = null; } catch (SearchPatternException ex) { _validationError = ex.Message; } } /// <summary> /// Reactivates the SearchPanel by setting the focus on the search box and selecting all text. /// </summary> public void Reactivate() { if (_searchTextBox == null) return; _searchTextBox.Focus(); _searchTextBox.SelectionStart = 0; _searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0; } /// <summary> /// Moves to the next occurrence in the file. /// </summary> public void FindNext() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ?? _renderer.CurrentResults.FirstSegment; if (result != null) { SelectResult(result); } } /// <summary> /// Moves to the previous occurrence in the file. /// </summary> public void FindPrevious() { var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset); if (result != null) result = _renderer.CurrentResults.GetPreviousSegment(result); if (result == null) result = _renderer.CurrentResults.LastSegment; if (result != null) { SelectResult(result); } } public void ReplaceNext() { if (!IsReplaceMode) return; FindNext(); if (!_textArea.Selection.IsEmpty) { _textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty); } UpdateSearch(); } public void ReplaceAll() { if (!IsReplaceMode) return; var replacement = ReplacePattern ?? string.Empty; var document = _textArea.Document; using (document.RunUpdate()) { var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray(); foreach (var textSegment in segments) { document.Replace(textSegment.StartOffset, textSegment.Length, new StringTextSource(replacement)); } } } private Popup _messageView; private ContentPresenter _messageViewContent; private string _validationError; private void DoSearch(bool changeSelection) { if (IsClosed) return; _renderer.CurrentResults.Clear(); if (!string.IsNullOrEmpty(SearchPattern)) { var offset = _textArea.Caret.Offset; if (changeSelection) { _textArea.ClearSelection(); } // We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>()) { if (changeSelection && result.StartOffset >= offset) { SelectResult(result); changeSelection = false; } _renderer.CurrentResults.Add(result); } } if (_messageView != null) { if (!_renderer.CurrentResults.Any()) { _messageViewContent.Content = SR.SearchNoMatchesFoundText; _messageView.PlacementTarget = _searchTextBox; _messageView.IsOpen = true; } else _messageView.IsOpen = false; } _textArea.TextView.InvalidateLayer(KnownLayer.Selection); } private void SelectResult(TextSegment result) { _textArea.Caret.Offset = result.StartOffset; _textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset); double distanceToViewBorder = _border == null ? Caret.MinimumDistanceToViewBorder : _border.Bounds.Height + _textArea.TextView.DefaultLineHeight; _textArea.Caret.BringCaretToView(distanceToViewBorder); // show caret even if the editor does not have the Keyboard Focus _textArea.Caret.Show(); } private void SearchLayerKeyDown(object sender, KeyEventArgs e) { switch (e.Key) Close(); break; } } /// <summary> { FindNext(); } if (_searchTextBox != null) { if (_validationError != null) { _messageViewContent.Content = SR.SearchErrorText + " " + _validationError; { var hasFocus = IsFocused; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) Close(); break; } } /// <summary> /// Gets whether the Panel is already closed. /// </summary> public bool IsClosed { get; private set; } /// <summary> /// Gets whether the Panel is currently opened. /// </summary> public bool IsOpened => !IsClosed; /// <summary> /// Closes the SearchPanel. /// </summary> public void Close() { _textArea.RemoveChild(this); _messageView.IsOpen = false; { if (!IsClosed) return; AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; _textArea.Focus(); } /// <summary> /// Opens the an existing search panel. /// </summary> public void Open() { if (!IsClosed) return; _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false; DoSearch(false); } protected override void OnPointerPressed(PointerPressedEventArgs e) { e.Handled = true; base.OnPointerPressed(e); } protected override void OnPointerMoved(PointerEventArgs e) { Cursor = Cursor.Default; base.OnPointerMoved(e); } protected override void OnGotFocus(GotFocusEventArgs e) { e.Handled = true; base.OnGotFocus(e); } /// <summary> /// Fired when SearchOptions are changed inside the SearchPanel. /// </summary> public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged; /// <summary> /// Raises the <see cref="SearchOptionsChanged" /> event. /// </summary> protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e) { SearchOptionsChanged?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); } /// <summary> /// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event. /// </summary> public class SearchOptionsChangedEventArgs : EventArgs { /// <summary> /// Gets the search pattern. /// </summary> public string SearchPattern { get; } /// <summary> /// Gets whether the search pattern should be interpreted case-sensitive. /// </summary> public bool MatchCase { get; } /// <summary> /// Gets whether the search pattern should be interpreted as regular expression. /// </summary> public bool UseRegex { get; } /// <summary> /// Gets whether the search pattern should only match whole words. /// </summary> public bool WholeWords { get; } /// <summary> /// Creates a new SearchOptionsChangedEventArgs instance. /// </summary> public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords) { SearchPattern = searchPattern; MatchCase = matchCase; UseRegex = useRegex; WholeWords = wholeWords; } } } <MSG> Dont install SearchPanel in adorner layer as doesnt receive input <DFF> @@ -24,6 +24,7 @@ using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; @@ -102,7 +103,7 @@ namespace AvaloniaEdit.Search set => SetValue(SearchPatternProperty, value); } - public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = + public static readonly AvaloniaProperty<bool> IsReplaceModeProperty = AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode)); public bool IsReplaceMode @@ -111,7 +112,7 @@ namespace AvaloniaEdit.Search set => SetValue(IsReplaceModeProperty, value); } - public static readonly AvaloniaProperty<string> ReplacePatternProperty = + public static readonly AvaloniaProperty<string> ReplacePatternProperty = AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern)); public string ReplacePattern @@ -242,7 +243,6 @@ namespace AvaloniaEdit.Search private void AttachInternal(TextArea textArea) { _textArea = textArea; - this[AdornerLayer.AdornedElementProperty] = textArea; _renderer = new SearchResultBackgroundRenderer(); _currentDocument = textArea.Document; @@ -453,6 +453,8 @@ namespace AvaloniaEdit.Search Close(); break; } + + e.Handled = true; } /// <summary> @@ -467,7 +469,7 @@ namespace AvaloniaEdit.Search { var hasFocus = IsFocused; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Remove(this); + _textArea.RemoveChild(this); _messageView.IsOpen = false; _textArea.TextView.BackgroundRenderers.Remove(_renderer); if (hasFocus) @@ -496,7 +498,7 @@ namespace AvaloniaEdit.Search { if (!IsClosed) return; - AdornerLayer.GetAdornerLayer(_textArea)?.Children.Add(this); + _textArea.AddChild(this); _textArea.TextView.BackgroundRenderers.Add(_renderer); IsClosed = false;
7
Dont install SearchPanel in adorner layer as doesnt receive input
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061649
<NME> injection.md <BEF> ## DOM injection Once you have [assembled](layout-assembly.md) and [rendered](rendering.md) your View you'll want to inject it into the DOM at some point. *FruitMachine* has multiple ways of doing this: - `.inject(<Element>)` Empties the contents of the given element, then appends `view.el`. - `.appendTo(<Element>)` Appends `view.el` to the given Element. - `.appendTo(<Element>, <Element>)` Appends `view.el` to the given Element, inserting before the second Element parameter. ### `View#inject()` ```js var container = document.querySelector('.container'); var apple = new Apple(); apple.render(); apple.inject(container); ``` ### `View#appendTo()` ```js var list = document.querySelector('.list'); var apple = new Apple(); apple.render(); apple.appendTo(list); ``` <MSG> Update docs <DFF> @@ -4,7 +4,7 @@ Once you have [assembled](layout-assembly.md) and [rendered](rendering.md) your - `.inject(<Element>)` Empties the contents of the given element, then appends `view.el`. - `.appendTo(<Element>)` Appends `view.el` to the given Element. -- `.appendTo(<Element>, <Element>)` Appends `view.el` to the given Element, inserting before the second Element parameter. +- `.insertBefore(<Element>, <Element>)` Appends `view.el` to the given Element as a previous sibling of the second Element parameter. ### `View#inject()`
1
Update docs
1
.md
md
mit
ftlabs/fruitmachine