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
|
---|---|---|---|---|---|---|---|---|
10060550 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060551 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060552 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060553 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060554 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060555 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060556 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060557 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060558 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060559 | <NME> AvaloniaEdit.Demo.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win7-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<EnableDefaultCompileItems>False</EnableDefaultCompileItems>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="**\*.cs" Exclude="obj\**" />
</ItemGroup>
<ItemGroup>
<Compile Update="**\*.xaml.cs">
<DependentUpon>%(Filename)</DependentUpon>
<SubType>Code</SubType>
</Compile>
<AvaloniaResource Include="Assets\**" />
<AvaloniaResource Include="**\*.xaml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
<PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
<PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
</ItemGroup>
<ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
<ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
</ItemGroup>
</Project>
<MSG> Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages
Feature/ci publish nuget packages
<DFF> @@ -25,8 +25,7 @@
<PackageReference Include="Avalonia.Desktop" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Gtk3" Version="0.4.1-build2959-alpha" />
<PackageReference Include="Avalonia.Skia.Linux.Natives" Version="1.56.1.3" />
- <PackageReference Include="SkiaSharp" Version="1.56.1" Condition="'$(TargetFramework)' == 'netcoreapp1.1'"/>
- <PackageReference Include="SkiaSharp" Version="1.57.0" Condition="'$(TargetFramework)' != 'netcoreapp1.1'"/>
+ <PackageReference Include="SkiaSharp" Version="1.56.1" />
</ItemGroup>
<ItemGroup>
| 1 | Merge pull request #13 from danwalmsley/feature/ci-publish-nuget-packages | 2 | .csproj | Demo/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10060560 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060561 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060562 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060563 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060564 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060565 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060566 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060567 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060568 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060569 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060570 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060571 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060572 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060573 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060574 | <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 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;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
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
{
#region Constructor
static TextArea()
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// 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()
{
/// </summary>
public Caret Caret { get; }
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
/// 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();
}
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
}
/// <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> implement ILogicalScrollable interface.
<DFF> @@ -16,19 +16,7 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Linq;
using Avalonia;
-using AvaloniaEdit.Document;
-using AvaloniaEdit.Indentation;
-using AvaloniaEdit.Rendering;
-using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
@@ -36,13 +24,25 @@ using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
+using AvaloniaEdit.Document;
+using AvaloniaEdit.Indentation;
+using AvaloniaEdit.Rendering;
+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
+ public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
#region Constructor
static TextArea()
@@ -563,12 +563,33 @@ namespace AvaloniaEdit.Editing
/// </summary>
public Caret Caret { get; }
+ public void ScrollToLine(int line, double borderSizePc = 0.5)
+ {
+ var offset = line - (Viewport.Height * borderSizePc);
+
+ if (offset < 0)
+ {
+ offset = 0;
+ }
+
+ this.BringIntoView(new Rect(1, offset, 0, 1));
+
+ offset = line + (Viewport.Height * borderSizePc);
+
+ 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);
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
@@ -936,7 +957,103 @@ namespace AvaloniaEdit.Editing
TextCopied?.Invoke(this, e);
}
+ private int LogicalScrollSize
+ {
+ get
+ {
+ if (TextView?.Document != null)
+ {
+ return TextView.Document.LineCount + 2;
+ }
+
+ return 2;
+ }
+ }
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var result = availableSize;
+
+ if (TextView?.Document != null)
+ {
+ result = new Size(availableSize.Width, LogicalScrollSize * TextView.DefaultLineHeight);
+
+ base.MeasureOverride(result);
+ }
+
+ return result;
+ }
+
+ protected override Size ArrangeOverride(Size finalSize)
+ {
+ if (TextView?.Document != null)
+ {
+ Viewport = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight);
+ Extent = new Size(finalSize.Width, LogicalScrollSize);
+
+ InvalidateScroll.Invoke();
+ }
+
+ var result = finalSize;
+ var arrangeOffset = new Vector(Math.Floor(Offset.X) * 10, Math.Floor(Offset.Y) * TextView.DefaultLineHeight);
+
+ result = base.ArrangeOverride(new Size(result.Width, result.Height + arrangeOffset.Y));
+
+ return result;
+ }
+
+ public bool BringIntoView(IControl target, Rect targetRect)
+ {
+ var result = false;
+
+ if (Offset.Y > targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, targetRect.Y * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ if (Offset.Y + Viewport.Height < targetRect.Y)
+ {
+ TextView?.SetScrollOffset(new Vector(targetRect.X, (targetRect.Y - Viewport.Height) * TextView.DefaultLineHeight));
+ result = true;
+ }
+
+ return result;
+ }
+
+ public IControl GetControlInDirection(NavigationDirection direction, IControl from)
+ {
+ return null;
+ }
+
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
+
+ public bool IsLogicalScrollEnabled => true;
+
+ public Action InvalidateScroll { get; set; }
+
+ public Size ScrollSize => new Size(Bounds.Width, 2);
+
+ public Size PageScrollSize => throw new NotImplementedException();
+
+ public Size Extent { get; private set; }
+
+ private Vector _offset;
+ public Vector Offset
+ {
+ get
+ {
+ return _offset;
+ }
+ set
+ {
+ _offset = value;
+
+ TextView?.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
+ }
+ }
+
+ public Size Viewport { get; private set; }
}
/// <summary>
| 130 | implement ILogicalScrollable interface. | 13 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060575 | <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);
};
// to add custom insteractions and logic to more complex modules.
// Redefining any of the View.prototype methods will overwrite them.
FruitMachine.module = function(type, props) {
if ('string' === typeof type) {
props.module = type;
return store.modules[type] = View.inherit(props);
} else if ('object' === typeof type) {
return View.inherit(type);
}
};
<MSG> Improved extension logic to allow views to extend from other views
<DFF> @@ -829,11 +829,34 @@
// to add custom insteractions and logic to more complex modules.
// Redefining any of the View.prototype methods will overwrite them.
FruitMachine.module = function(type, props) {
+
+ // If a type has been given, we store
+ // the View so that it can be referenced
+ // by its type in later layout definitions.
if ('string' === typeof type) {
props.module = type;
- return store.modules[type] = View.inherit(props);
+
+ // If a 'props' has the '__super__'
+ // key then we can assume it has been
+ // extended from an existing View. In
+ // this case we just store it. If it
+ // is just an object, then we extend
+ // View with the passed object.
+ //
+ // REVIEW:
+ // This checkout should be more solid,
+ // how can we check a view has originally
+ // been extended from a FruitMachine View?
+ if (props.__super__) return store.modules[type] = props;
+ else return store.modules[type] = View.inherit(props);
+
+ // If type is an object then we assume
+ // no type has been passed. We don't store
+ // the object and just pass back an extened
+ // default FruitMachine View.
} else if ('object' === typeof type) {
- return View.inherit(type);
+ props = type;
+ return View.inherit(props);
}
};
| 25 | Improved extension logic to allow views to extend from other views | 2 | .js | js | mit | ftlabs/fruitmachine |
10060576 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060577 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060578 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060579 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060580 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060581 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060582 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060583 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060584 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060585 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060586 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060587 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060588 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060589 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060590 | <NME> TSQL-Mode.xshd
<BEF> ADDFILE
<MSG> Add TSQL language definitions #107
https://github.com/icsharpcode/AvalonEdit/pull/107
<DFF> @@ -0,0 +1,617 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="TSQL" extensions=".sql" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+ <Color name="Comment" foreground="Green" exampleText="-- comment" />
+ <Color name="Char" foreground="Red" exampleText="name = 'abc'"/>
+ <Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="SELECT FROM"/>
+
+ <Property name="DocCommentMarker" value="///" />
+
+ <RuleSet name="CommentMarkerSet">
+ <Keywords fontWeight="bold" foreground="Red">
+ <Word>TODO</Word>
+ <Word>FIXME</Word>
+ </Keywords>
+ <Keywords fontWeight="bold" foreground="#E0E000">
+ <Word>HACK</Word>
+ <Word>UNDONE</Word>
+ </Keywords>
+ </RuleSet>
+
+ <RuleSet ignoreCase="true">
+ <Span color="Comment" ruleSet="CommentMarkerSet">
+ <Begin>--</Begin>
+ </Span>
+
+ <Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+ <Begin>/\*</Begin>
+ <End>\*/</End>
+ </Span>
+
+ <Span color="Char">
+ <Begin>'</Begin>
+ <End>'</End>
+ <RuleSet>
+ <Span begin="\\" end="."/>
+ </RuleSet>
+ </Span>
+
+ <Keywords color="Keywords">
+ <Word>abs</Word>
+ <Word>absolute</Word>
+ <Word>access</Word>
+ <Word>acos</Word>
+ <Word>add</Word>
+ <Word>add_months</Word>
+ <Word>adddate</Word>
+ <Word>admin</Word>
+ <Word>after</Word>
+ <Word>aggregate</Word>
+ <Word>all</Word>
+ <Word>allocate</Word>
+ <Word>alter</Word>
+ <Word>and</Word>
+ <Word>any</Word>
+ <Word>app_name</Word>
+ <Word>are</Word>
+ <Word>array</Word>
+ <Word>as</Word>
+ <Word>asc</Word>
+ <Word>ascii</Word>
+ <Word>asin</Word>
+ <Word>assertion</Word>
+ <Word>at</Word>
+ <Word>atan</Word>
+ <Word>atn2</Word>
+ <Word>audit</Word>
+ <Word>authid</Word>
+ <Word>authorization</Word>
+ <Word>autonomous_transaction</Word>
+ <Word>avg</Word>
+ <Word>before</Word>
+ <Word>begin</Word>
+ <Word>benchmark</Word>
+ <Word>between</Word>
+ <Word>bfilename</Word>
+ <Word>bigint</Word>
+ <Word>bin</Word>
+ <Word>binary</Word>
+ <Word>binary_checksum</Word>
+ <Word>binary_integer</Word>
+ <Word>bit</Word>
+ <Word>bit_count</Word>
+ <Word>bit_and</Word>
+ <Word>bit_or</Word>
+ <Word>blob</Word>
+ <Word>body</Word>
+ <Word>boolean</Word>
+ <Word>both</Word>
+ <Word>breadth</Word>
+ <Word>bulk</Word>
+ <Word>by</Word>
+ <Word>call</Word>
+ <Word>cascade</Word>
+ <Word>cascaded</Word>
+ <Word>case</Word>
+ <Word>cast</Word>
+ <Word>catalog</Word>
+ <Word>ceil</Word>
+ <Word>ceiling</Word>
+ <Word>char</Word>
+ <Word>char_base</Word>
+ <Word>character</Word>
+ <Word>charindex</Word>
+ <Word>chartorowid</Word>
+ <Word>check</Word>
+ <Word>checksum</Word>
+ <Word>checksum_agg</Word>
+ <Word>chr</Word>
+ <Word>class</Word>
+ <Word>clob</Word>
+ <Word>close</Word>
+ <Word>cluster</Word>
+ <Word>coalesce</Word>
+ <Word>col_length</Word>
+ <Word>col_name</Word>
+ <Word>collate</Word>
+ <Word>collation</Word>
+ <Word>collect</Word>
+ <Word>column</Word>
+ <Word>comment</Word>
+ <Word>commit</Word>
+ <Word>completion</Word>
+ <Word>compress</Word>
+ <Word>concat</Word>
+ <Word>concat_ws</Word>
+ <Word>connect</Word>
+ <Word>connection</Word>
+ <Word>constant</Word>
+ <Word>constraint</Word>
+ <Word>constraints</Word>
+ <Word>constructorcreate</Word>
+ <Word>contains</Word>
+ <Word>containsable</Word>
+ <Word>continue</Word>
+ <Word>conv</Word>
+ <Word>convert</Word>
+ <Word>corr</Word>
+ <Word>corresponding</Word>
+ <Word>cos</Word>
+ <Word>cot</Word>
+ <Word>count</Word>
+ <Word>count_big</Word>
+ <Word>covar_pop</Word>
+ <Word>covar_samp</Word>
+ <Word>create</Word>
+ <Word>cross</Word>
+ <Word>cube</Word>
+ <Word>cume_dist</Word>
+ <Word>current</Word>
+ <Word>current_date</Word>
+ <Word>current_path</Word>
+ <Word>current_role</Word>
+ <Word>current_time</Word>
+ <Word>current_timestamp</Word>
+ <Word>current_user</Word>
+ <Word>currval</Word>
+ <Word>cursor</Word>
+ <Word>cycle</Word>
+ <Word>data</Word>
+ <Word>datalength</Word>
+ <Word>databasepropertyex</Word>
+ <Word>date</Word>
+ <Word>date_add</Word>
+ <Word>date_format</Word>
+ <Word>date_sub</Word>
+ <Word>dateadd</Word>
+ <Word>datediff</Word>
+ <Word>datename</Word>
+ <Word>datepart</Word>
+ <Word>datetime</Word>
+ <Word>day</Word>
+ <Word>db_id</Word>
+ <Word>db_name</Word>
+ <Word>deallocate</Word>
+ <Word>dec</Word>
+ <Word>declare</Word>
+ <Word>decimal</Word>
+ <Word>decode</Word>
+ <Word>default</Word>
+ <Word>deferrable</Word>
+ <Word>deferred</Word>
+ <Word>degrees</Word>
+ <Word>delete</Word>
+ <Word>dense_rank</Word>
+ <Word>depth</Word>
+ <Word>deref</Word>
+ <Word>desc</Word>
+ <Word>describe</Word>
+ <Word>descriptor</Word>
+ <Word>destroy</Word>
+ <Word>destructor</Word>
+ <Word>deterministic</Word>
+ <Word>diagnostics</Word>
+ <Word>dictionary</Word>
+ <Word>disconnect</Word>
+ <Word>difference</Word>
+ <Word>distinct</Word>
+ <Word>do</Word>
+ <Word>domain</Word>
+ <Word>double</Word>
+ <Word>drop</Word>
+ <Word>dump</Word>
+ <Word>dynamic</Word>
+ <Word>each</Word>
+ <Word>else</Word>
+ <Word>elsif</Word>
+ <Word>empth</Word>
+ <Word>encode</Word>
+ <Word>encrypt</Word>
+ <Word>end</Word>
+ <Word>end-exec</Word>
+ <Word>equals</Word>
+ <Word>escape</Word>
+ <Word>every</Word>
+ <Word>except</Word>
+ <Word>exception</Word>
+ <Word>exclusive</Word>
+ <Word>exec</Word>
+ <Word>execute</Word>
+ <Word>exists</Word>
+ <Word>exit</Word>
+ <Word>exp</Word>
+ <Word>export_set</Word>
+ <Word>extends</Word>
+ <Word>external</Word>
+ <Word>extract</Word>
+ <Word>false</Word>
+ <Word>fetch</Word>
+ <Word>first</Word>
+ <Word>first_value</Word>
+ <Word>file</Word>
+ <Word>float</Word>
+ <Word>floor</Word>
+ <Word>file_id</Word>
+ <Word>file_name</Word>
+ <Word>filegroup_id</Word>
+ <Word>filegroup_name</Word>
+ <Word>filegroupproperty</Word>
+ <Word>fileproperty</Word>
+ <Word>for</Word>
+ <Word>forall</Word>
+ <Word>foreign</Word>
+ <Word>format</Word>
+ <Word>formatmessage</Word>
+ <Word>found</Word>
+ <Word>freetexttable</Word>
+ <Word>from</Word>
+ <Word>from_days</Word>
+ <Word>fulltextcatalog</Word>
+ <Word>fulltextservice</Word>
+ <Word>function</Word>
+ <Word>general</Word>
+ <Word>get</Word>
+ <Word>get_lock</Word>
+ <Word>getdate</Word>
+ <Word>getansinull</Word>
+ <Word>getutcdate</Word>
+ <Word>global</Word>
+ <Word>go</Word>
+ <Word>goto</Word>
+ <Word>grant</Word>
+ <Word>greatest</Word>
+ <Word>group</Word>
+ <Word>grouping</Word>
+ <Word>having</Word>
+ <Word>heap</Word>
+ <Word>hex</Word>
+ <Word>hextoraw</Word>
+ <Word>host</Word>
+ <Word>host_id</Word>
+ <Word>host_name</Word>
+ <Word>hour</Word>
+ <Word>ident_incr</Word>
+ <Word>ident_seed</Word>
+ <Word>ident_current</Word>
+ <Word>identified</Word>
+ <Word>identity</Word>
+ <Word>if</Word>
+ <Word>ifnull</Word>
+ <Word>ignore</Word>
+ <Word>immediate</Word>
+ <Word>in</Word>
+ <Word>increment</Word>
+ <Word>index</Word>
+ <Word>index_col</Word>
+ <Word>indexproperty</Word>
+ <Word>indicator</Word>
+ <Word>initcap</Word>
+ <Word>initial</Word>
+ <Word>initialize</Word>
+ <Word>initially</Word>
+ <Word>inner</Word>
+ <Word>inout</Word>
+ <Word>input</Word>
+ <Word>insert</Word>
+ <Word>instr</Word>
+ <Word>instrb</Word>
+ <Word>int</Word>
+ <Word>integer</Word>
+ <Word>interface</Word>
+ <Word>intersect</Word>
+ <Word>interval</Word>
+ <Word>into</Word>
+ <Word>is</Word>
+ <Word>is_member</Word>
+ <Word>is_srvrolemember</Word>
+ <Word>is_null</Word>
+ <Word>is_numeric</Word>
+ <Word>isdate</Word>
+ <Word>isnull</Word>
+ <Word>isolation</Word>
+ <Word>iterate</Word>
+ <Word>java</Word>
+ <Word>join</Word>
+ <Word>key</Word>
+ <Word>lag</Word>
+ <Word>language</Word>
+ <Word>large</Word>
+ <Word>last</Word>
+ <Word>last_day</Word>
+ <Word>last_value</Word>
+ <Word>lateral</Word>
+ <Word>lcase</Word>
+ <Word>lead</Word>
+ <Word>leading</Word>
+ <Word>least</Word>
+ <Word>left</Word>
+ <Word>len</Word>
+ <Word>length</Word>
+ <Word>lengthb</Word>
+ <Word>less</Word>
+ <Word>level</Word>
+ <Word>like</Word>
+ <Word>limit</Word>
+ <Word>limited</Word>
+ <Word>ln</Word>
+ <Word>lpad</Word>
+ <Word>local</Word>
+ <Word>localtime</Word>
+ <Word>localtimestamp</Word>
+ <Word>locator</Word>
+ <Word>lock</Word>
+ <Word>log</Word>
+ <Word>log10</Word>
+ <Word>long</Word>
+ <Word>loop</Word>
+ <Word>lower</Word>
+ <Word>ltrim</Word>
+ <Word>make_ref</Word>
+ <Word>map</Word>
+ <Word>match</Word>
+ <Word>max</Word>
+ <Word>maxextents</Word>
+ <Word>mid</Word>
+ <Word>min</Word>
+ <Word>minus</Word>
+ <Word>minute</Word>
+ <Word>mlslabel</Word>
+ <Word>mod</Word>
+ <Word>mode</Word>
+ <Word>modifies</Word>
+ <Word>modify</Word>
+ <Word>module</Word>
+ <Word>month</Word>
+ <Word>months_between</Word>
+ <Word>names</Word>
+ <Word>national</Word>
+ <Word>natural</Word>
+ <Word>naturaln</Word>
+ <Word>nchar</Word>
+ <Word>nclob</Word>
+ <Word>new</Word>
+ <Word>new_time</Word>
+ <Word>newid</Word>
+ <Word>next</Word>
+ <Word>next_day</Word>
+ <Word>nextval</Word>
+ <Word>no</Word>
+ <Word>noaudit</Word>
+ <Word>nocompress</Word>
+ <Word>nocopy</Word>
+ <Word>nolock</Word>
+ <Word>none</Word>
+ <Word>not</Word>
+ <Word>nowait</Word>
+ <Word>null</Word>
+ <Word>nullif</Word>
+ <Word>number</Word>
+ <Word>number_base</Word>
+ <Word>numeric</Word>
+ <Word>nvl</Word>
+ <Word>nvl2</Word>
+ <Word>object</Word>
+ <Word>object_id</Word>
+ <Word>object_name</Word>
+ <Word>object_property</Word>
+ <Word>ocirowid</Word>
+ <Word>oct</Word>
+ <Word>of</Word>
+ <Word>off</Word>
+ <Word>offline</Word>
+ <Word>old</Word>
+ <Word>on</Word>
+ <Word>online</Word>
+ <Word>only</Word>
+ <Word>opaque</Word>
+ <Word>open</Word>
+ <Word>operator</Word>
+ <Word>operation</Word>
+ <Word>option</Word>
+ <Word>or</Word>
+ <Word>ord</Word>
+ <Word>order</Word>
+ <Word>ordinalityorganization</Word>
+ <Word>others</Word>
+ <Word>out</Word>
+ <Word>outer</Word>
+ <Word>output</Word>
+ <Word>package</Word>
+ <Word>pad</Word>
+ <Word>parameter</Word>
+ <Word>parameters</Word>
+ <Word>partial</Word>
+ <Word>partition</Word>
+ <Word>path</Word>
+ <Word>pctfree</Word>
+ <Word>percent_rank</Word>
+ <Word>pi</Word>
+ <Word>pls_integer</Word>
+ <Word>positive</Word>
+ <Word>positiven</Word>
+ <Word>postfix</Word>
+ <Word>pow</Word>
+ <Word>power</Word>
+ <Word>pragma</Word>
+ <Word>precision</Word>
+ <Word>prefix</Word>
+ <Word>preorder</Word>
+ <Word>prepare</Word>
+ <Word>preserve</Word>
+ <Word>primary</Word>
+ <Word>prior</Word>
+ <Word>private</Word>
+ <Word>privileges</Word>
+ <Word>procedure</Word>
+ <Word>public</Word>
+ <Word>radians</Word>
+ <Word>raise</Word>
+ <Word>rand</Word>
+ <Word>range</Word>
+ <Word>rank</Word>
+ <Word>ratio_to_export</Word>
+ <Word>raw</Word>
+ <Word>rawtohex</Word>
+ <Word>read</Word>
+ <Word>reads</Word>
+ <Word>real</Word>
+ <Word>record</Word>
+ <Word>recursive</Word>
+ <Word>ref</Word>
+ <Word>references</Word>
+ <Word>referencing</Word>
+ <Word>reftohex</Word>
+ <Word>relative</Word>
+ <Word>release</Word>
+ <Word>release_lock</Word>
+ <Word>rename</Word>
+ <Word>repeat</Word>
+ <Word>replace</Word>
+ <Word>resource</Word>
+ <Word>restrict</Word>
+ <Word>result</Word>
+ <Word>return</Word>
+ <Word>returns</Word>
+ <Word>reverse</Word>
+ <Word>revoke</Word>
+ <Word>right</Word>
+ <Word>rollback</Word>
+ <Word>rollup</Word>
+ <Word>round</Word>
+ <Word>routine</Word>
+ <Word>row</Word>
+ <Word>row_number</Word>
+ <Word>rowid</Word>
+ <Word>rowidtochar</Word>
+ <Word>rowlabel</Word>
+ <Word>rowlock</Word>
+ <Word>rownum</Word>
+ <Word>rows</Word>
+ <Word>rowtype</Word>
+ <Word>rpad</Word>
+ <Word>rtrim</Word>
+ <Word>savepoint</Word>
+ <Word>schema</Word>
+ <Word>scroll</Word>
+ <Word>scope</Word>
+ <Word>search</Word>
+ <Word>second</Word>
+ <Word>section</Word>
+ <Word>seddev_samp</Word>
+ <Word>select</Word>
+ <Word>separate</Word>
+ <Word>sequence</Word>
+ <Word>session</Word>
+ <Word>session_user</Word>
+ <Word>set</Word>
+ <Word>sets</Word>
+ <Word>share</Word>
+ <Word>sign</Word>
+ <Word>sin</Word>
+ <Word>sinh</Word>
+ <Word>size</Word>
+ <Word>smallint</Word>
+ <Word>some</Word>
+ <Word>soundex</Word>
+ <Word>space</Word>
+ <Word>specific</Word>
+ <Word>specifictype</Word>
+ <Word>sql</Word>
+ <Word>sqlcode</Word>
+ <Word>sqlerrm</Word>
+ <Word>sqlexception</Word>
+ <Word>sqlstate</Word>
+ <Word>sqlwarning</Word>
+ <Word>sqrt</Word>
+ <Word>start</Word>
+ <Word>state</Word>
+ <Word>statement</Word>
+ <Word>static</Word>
+ <Word>std</Word>
+ <Word>stddev</Word>
+ <Word>stdev_pop</Word>
+ <Word>strcmp</Word>
+ <Word>structure</Word>
+ <Word>subdate</Word>
+ <Word>substr</Word>
+ <Word>substrb</Word>
+ <Word>substring</Word>
+ <Word>substring_index</Word>
+ <Word>subtype</Word>
+ <Word>successful</Word>
+ <Word>sum</Word>
+ <Word>synonym</Word>
+ <Word>sys_context</Word>
+ <Word>sys_guid</Word>
+ <Word>sysdate</Word>
+ <Word>system_user</Word>
+ <Word>table</Word>
+ <Word>tan</Word>
+ <Word>tanh</Word>
+ <Word>temporary</Word>
+ <Word>terminate</Word>
+ <Word>than</Word>
+ <Word>then</Word>
+ <Word>time</Word>
+ <Word>timestamp</Word>
+ <Word>timezone_abbr</Word>
+ <Word>timezone_minute</Word>
+ <Word>timezone_hour</Word>
+ <Word>timezone_region</Word>
+ <Word>tinyint</Word>
+ <Word>to</Word>
+ <Word>to_char</Word>
+ <Word>to_date</Word>
+ <Word>to_days</Word>
+ <Word>to_number</Word>
+ <Word>to_single_byte</Word>
+ <Word>trailing</Word>
+ <Word>transaction</Word>
+ <Word>translate</Word>
+ <Word>translation</Word>
+ <Word>treat</Word>
+ <Word>trigger</Word>
+ <Word>trim</Word>
+ <Word>true</Word>
+ <Word>trunc</Word>
+ <Word>truncate</Word>
+ <Word>type</Word>
+ <Word>ucase</Word>
+ <Word>uid</Word>
+ <Word>under</Word>
+ <Word>union</Word>
+ <Word>unique</Word>
+ <Word>unknown</Word>
+ <Word>unnest</Word>
+ <Word>update</Word>
+ <Word>upper</Word>
+ <Word>usage</Word>
+ <Word>use</Word>
+ <Word>user</Word>
+ <Word>userenv</Word>
+ <Word>using</Word>
+ <Word>validate</Word>
+ <Word>value</Word>
+ <Word>values</Word>
+ <Word>var_pop</Word>
+ <Word>var_samp</Word>
+ <Word>varbinary</Word>
+ <Word>varchar</Word>
+ <Word>varchar2</Word>
+ <Word>variable</Word>
+ <Word>variance</Word>
+ <Word>varying</Word>
+ <Word>view</Word>
+ <Word>vsize</Word>
+ <Word>when</Word>
+ <Word>whenever</Word>
+ <Word>where</Word>
+ <Word>with</Word>
+ <Word>without</Word>
+ <Word>while</Word>
+ <Word>work</Word>
+ <Word>write</Word>
+ <Word>year</Word>
+ <Word>zone</Word>
+ </Keywords>
+ </RuleSet>
+</SyntaxDefinition>
\ No newline at end of file
| 617 | Add TSQL language definitions #107 | 0 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10060591 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060592 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060593 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060594 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060595 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060596 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060597 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060598 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060599 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060600 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060601 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060602 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060603 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060604 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060605 | <NME> .gitignore
<BEF> ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# Visual Studio Code
.vscode/
<MSG> ignore the tools dir (cake build system)
<DFF> @@ -2,6 +2,7 @@
## files generated by popular Visual Studio add-ons.
# User-specific files
+tools/
*.suo
*.user
*.userosscache
| 1 | ignore the tools dir (cake build system) | 0 | gitignore | mit | AvaloniaUI/AvaloniaEdit |
|
10060606 | <NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components.  ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links ## Fields ## Methods Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true){ return "Yes" } else{ return "No" } } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ... } // called on loading finish } ``` This simple example prints messages to console instead of showing load indicator: ```javascript { loadIndicator: { show: function() { console.log("loading started"); }, hide: function() { console.log("loading finished"); } } } ``` If `loadIndicator` is a function, it accepts the config of load indicator in the following format: ```javascript { container, // grid container div message, // the loading message is a value of the option loadMessage shading // the boolean value defining whether to show shading. This is a value of the option loadShading } ``` The similar example printing messages to console shows how to configure loading indicator with a function returning an object: ```javascript { loadIndicator: function(config) { return { show: function() { console.log("loading started: " + config.message); }, hide: function() { console.log("loading finished"); } }; } } ``` Customization of loading indicator is useful, when you want to use any external load indicator that is used for all other ajax requests on the page. This example shows how to use [spin.js](http://fgnass.github.io/spin.js/) to indicate loading: ```javascript { loadIndicator: function(config) { var container = config.container[0]; var spinner = new Spinner(); return { show: function() { spinner.spin(container); }, hide: function() { spinner.stop(); } }; } } ``` ## Requirement jQuery (1.8.3 or later) ## Compatibility **Desktop** * Chrome * Safari * Firefox * Opera 15+ * IE 8+ **Mobile** * Safari for iOS * Chrome for Android * IE10 for WP8 <MSG> Docs: Fields descriptions <DFF> @@ -373,7 +373,235 @@ The function should return markup as a string, jQueryElement or DomNode represen ## Fields +All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. +`jsGrid.fields` contains following build-in fields: + +````javascript + +{ + text: { ... }, // simple text input + number: { ... }, // number input + select: { ... }, // select control + checkbox: { ... }, // checkbox input + textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) + control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row +} + +```` + +Each build-in field can be easily customized with general configuration properties described in **fields** section of grid config description and custom field-specific properties described below. + +### text +Text field renders `<input type="text">` in filter, inserting and editing rows. + +Custom properties: + +````javascript + +{ + autosearch: true // triggers searching when the user presses `enter` key in the filter input +} + +```` + +### number +Number field renders `<input type="number">` in filter, inserting and editing rows. + +Custom properties: + +````javascript + +{ + sorter: "number", // uses sorter for numbers + align: "right" // right text alignment +} + +```` + +### select +Select field renders `<select>` control in filter, inserting and editing rows. + +Custom properties: + +````javascript + +{ + align: "center", // center text alignment + autosearch: true, // triggers searching when the user changes the selected item in the filter + items: [], // an array of items for select + valueField: "", // name of property of item to be used as value + textField = "", // name of property of item to be used as displaying value + selectedIndex: -1 // index of selected item by default +} + +```` + +If valueField is not defined, then the item index is used instead. +If textField is not defined, then item itself is used to display value. + +For instance the simple select field config may look like: + +````javascript + +{ + name: "Country", + type: "select", + items: [ "", "United States", "Canada", "United Kingdom" ] +} + +```` + +or more complex with items as objects: + +````javascript + +{ + name: "Country", + type: "select" + items: [ + { Name: "", Id: 0 }, + { Name: "United States", Id: 1 }, + { Name: "Canada", Id: 2 }, + { Name: "United Kingdom", Id: 3 } + ], + valueField: "Id", + textField: "Name" +} + +```` + +### checkbox +Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. +Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). + +Custom properties: + +````javascript + +{ + sorter: "number", // uses sorter for numbers + align: "center" // center text alignment + autosearch: true // triggers searching when the user clicks checkbox in filter +} + +```` + +### textarea +Textarea field renders '<textarea>` in inserting and editing rows and `<input type="text">` in filter row. + +Custom properties: + +````javascript + +{ + autosearch: true // triggers searching when the user presses `enter` key in the filter input +} + +```` + +### control +Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. +It also renders button switching between filtering and searching in header row. + +Custom properties: + +````javascript + +{ + editButton: true, // show edit button + deleteButton: true, // show delete button + clearFilterButton: true, // show clear filter button + modeSwitchButton: true, // show switching filtering/inserting button + + align: "center", // center content alignment + width: 50, // default column width is 50px + filtering: false, // disable filtering for column + inserting: false, // disable inserting for column + editing: false, // disable editing for column + sorting: false, // disable sorting for column + + searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode + insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode + editButtonTooltip: "Edit", // tooltip of edit item button + deleteButtonTooltip: "Delete", // tooltip of delete item button + searchButtonTooltip: "Search", // tooltip of search button + clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button + insertButtonTooltip: "Insert", // tooltip of insert button + updateButtonTooltip: "Update", // tooltip of update item button + cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button +} + +```` + +### Custom Field + +If you need a completely custom field, the object `jsGrid.fields` can be easily extended. + +In this example we define new grid field `date`: + +````javascript + +var MyDateField = function(config) { + jsGrid.Field.call(this, config); +}; + +MyDateField.prototype = new jsGrid.Field({ + + css: "date-field", // redefine general property 'css' + align: "center", // redefine general property 'align' + + myCustomProperty: "foo", // custom property + + sorter: function(date1, date2) { + return new Date(date1) - new Date(date2); + }, + + itemTemplate: function(value) { + return new Date(value).toDateString(); + }, + + insertTemplate: function(value) { + return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); + }, + + editTemplate: function(value) { + return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); + }, + + insertValue: function() { + return this._insertPicker.datepicker("getDate").toISOString(); + }, + + editValue: function() { + return this._editPicker.datepicker("getDate").toISOString(); + } +}); + +jsGrid.fields.date = MyDateField; + +```` + +To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. +Here `itemTemplate` just returns the string representation of a date. +`insertTemplate` | 228 | Docs: Fields descriptions | 0 | .md | md | mit | tabalinas/jsgrid |
10060607 | <NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components.  ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links ## Fields ## Methods Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true){ return "Yes" } else{ return "No" } } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ... } // called on loading finish } ``` This simple example prints messages to console instead of showing load indicator: ```javascript { loadIndicator: { show: function() { console.log("loading started"); }, hide: function() { console.log("loading finished"); } } } ``` If `loadIndicator` is a function, it accepts the config of load indicator in the following format: ```javascript { container, // grid container div message, // the loading message is a value of the option loadMessage shading // the boolean value defining whether to show shading. This is a value of the option loadShading } ``` The similar example printing messages to console shows how to configure loading indicator with a function returning an object: ```javascript { loadIndicator: function(config) { return { show: function() { console.log("loading started: " + config.message); }, hide: function() { console.log("loading finished"); } }; } } ``` Customization of loading indicator is useful, when you want to use any external load indicator that is used for all other ajax requests on the page. This example shows how to use [spin.js](http://fgnass.github.io/spin.js/) to indicate loading: ```javascript { loadIndicator: function(config) { var container = config.container[0]; var spinner = new Spinner(); return { show: function() { spinner.spin(container); }, hide: function() { spinner.stop(); } }; } } ``` ## Requirement jQuery (1.8.3 or later) ## Compatibility **Desktop** * Chrome * Safari * Firefox * Opera 15+ * IE 8+ **Mobile** * Safari for iOS * Chrome for Android * IE10 for WP8 <MSG> Docs: Fields descriptions <DFF> @@ -373,7 +373,235 @@ The function should return markup as a string, jQueryElement or DomNode represen ## Fields +All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. +`jsGrid.fields` contains following build-in fields: + +````javascript + +{ + text: { ... }, // simple text input + number: { ... }, // number input + select: { ... }, // select control + checkbox: { ... }, // checkbox input + textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) + control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row +} + +```` + +Each build-in field can be easily customized with general configuration properties described in **fields** section of grid config description and custom field-specific properties described below. + +### text +Text field renders `<input type="text">` in filter, inserting and editing rows. + +Custom properties: + +````javascript + +{ + autosearch: true // triggers searching when the user presses `enter` key in the filter input +} + +```` + +### number +Number field renders `<input type="number">` in filter, inserting and editing rows. + +Custom properties: + +````javascript + +{ + sorter: "number", // uses sorter for numbers + align: "right" // right text alignment +} + +```` + +### select +Select field renders `<select>` control in filter, inserting and editing rows. + +Custom properties: + +````javascript + +{ + align: "center", // center text alignment + autosearch: true, // triggers searching when the user changes the selected item in the filter + items: [], // an array of items for select + valueField: "", // name of property of item to be used as value + textField = "", // name of property of item to be used as displaying value + selectedIndex: -1 // index of selected item by default +} + +```` + +If valueField is not defined, then the item index is used instead. +If textField is not defined, then item itself is used to display value. + +For instance the simple select field config may look like: + +````javascript + +{ + name: "Country", + type: "select", + items: [ "", "United States", "Canada", "United Kingdom" ] +} + +```` + +or more complex with items as objects: + +````javascript + +{ + name: "Country", + type: "select" + items: [ + { Name: "", Id: 0 }, + { Name: "United States", Id: 1 }, + { Name: "Canada", Id: 2 }, + { Name: "United Kingdom", Id: 3 } + ], + valueField: "Id", + textField: "Name" +} + +```` + +### checkbox +Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. +Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). + +Custom properties: + +````javascript + +{ + sorter: "number", // uses sorter for numbers + align: "center" // center text alignment + autosearch: true // triggers searching when the user clicks checkbox in filter +} + +```` + +### textarea +Textarea field renders '<textarea>` in inserting and editing rows and `<input type="text">` in filter row. + +Custom properties: + +````javascript + +{ + autosearch: true // triggers searching when the user presses `enter` key in the filter input +} + +```` + +### control +Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. +It also renders button switching between filtering and searching in header row. + +Custom properties: + +````javascript + +{ + editButton: true, // show edit button + deleteButton: true, // show delete button + clearFilterButton: true, // show clear filter button + modeSwitchButton: true, // show switching filtering/inserting button + + align: "center", // center content alignment + width: 50, // default column width is 50px + filtering: false, // disable filtering for column + inserting: false, // disable inserting for column + editing: false, // disable editing for column + sorting: false, // disable sorting for column + + searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode + insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode + editButtonTooltip: "Edit", // tooltip of edit item button + deleteButtonTooltip: "Delete", // tooltip of delete item button + searchButtonTooltip: "Search", // tooltip of search button + clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button + insertButtonTooltip: "Insert", // tooltip of insert button + updateButtonTooltip: "Update", // tooltip of update item button + cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button +} + +```` + +### Custom Field + +If you need a completely custom field, the object `jsGrid.fields` can be easily extended. + +In this example we define new grid field `date`: + +````javascript + +var MyDateField = function(config) { + jsGrid.Field.call(this, config); +}; + +MyDateField.prototype = new jsGrid.Field({ + + css: "date-field", // redefine general property 'css' + align: "center", // redefine general property 'align' + + myCustomProperty: "foo", // custom property + + sorter: function(date1, date2) { + return new Date(date1) - new Date(date2); + }, + + itemTemplate: function(value) { + return new Date(value).toDateString(); + }, + + insertTemplate: function(value) { + return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); + }, + + editTemplate: function(value) { + return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); + }, + + insertValue: function() { + return this._insertPicker.datepicker("getDate").toISOString(); + }, + + editValue: function() { + return this._editPicker.datepicker("getDate").toISOString(); + } +}); + +jsGrid.fields.date = MyDateField; + +```` + +To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. +Here `itemTemplate` just returns the string representation of a date. +`insertTemplate` | 228 | Docs: Fields descriptions | 0 | .md | md | mit | tabalinas/jsgrid |
10060608 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060609 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060610 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060611 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060612 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060613 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060614 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060615 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060616 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060617 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060618 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060619 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060620 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060621 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060622 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
_visual = null;
_textLines = null;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal
Fix VisualLine disposal
<DFF> @@ -657,10 +657,6 @@ namespace AvaloniaEdit.Rendering
{
((ISetLogicalParent)_visual).SetParent(null);
}
-
- _visual = null;
-
- _textLines = null;
}
/// <summary>
| 0 | Merge pull request #270 from AvaloniaUI/fixes/visualLineDisposal | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060623 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060624 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060625 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060626 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060627 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060628 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060629 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060630 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060631 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060632 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060633 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060634 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060635 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060636 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060637 | <NME> XmlnsAttributes.cs
<BEF> using Avalonia.Metadata;
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
[assembly: InternalsVisibleTo("AvaloniaEdit.Tests")]
<MSG> Merge pull request #16 from AvaloniaUI/search
Search panel
<DFF> @@ -1,7 +1,7 @@
using Avalonia.Metadata;
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Editing")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Rendering")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Highlighting")]
-[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "ICSharpCode.AvalonEdit.Search")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Editing")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Rendering")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Highlighting")]
+[assembly: XmlnsDefinition("https://github.com/avaloniaui/avaloniaedit", "AvaloniaEdit.Search")]
| 5 | Merge pull request #16 from AvaloniaUI/search | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060638 | <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
// in the current environment.
var hasDom = (typeof document !== 'undefined');
// Global data store
var store = {
modules: {},
templates: {},
helpers: {}
};
/**
* VIEW
*/
var Module = fm.modules[options.module];
if (Module) {
return new Module(options);
}
throw new Error("Unable to find module '" + options.module + "'");
// Current Version
FruitMachine.VERSION = '0.0.1';
// Utilities
var util = FruitMachine.util = {
// Mixin events and return
return events(fm);
};
<MSG> Made store object public
<DFF> @@ -39,13 +39,6 @@
// in the current environment.
var hasDom = (typeof document !== 'undefined');
- // Global data store
- var store = {
- modules: {},
- templates: {},
- helpers: {}
- };
-
/**
* VIEW
*/
@@ -57,6 +50,13 @@
// Current Version
FruitMachine.VERSION = '0.0.1';
+ // Global data store
+ var store = FruitMachine.store = {
+ modules: {},
+ templates: {},
+ helpers: {}
+ };
+
// Utilities
var util = FruitMachine.util = {
| 7 | Made store object public | 7 | .js | js | mit | ftlabs/fruitmachine |
10060639 | <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);
};
// Hook for plugins so that functionality
// can be triggered before Fruit Machine
// object initialization.
FruitMachine.trigger('beforeinitialize');
this.initialize.call(this, options);
};
// Run teardown so custom
// views can bind logic to it
this.teardown(options);
// Hook for plugins so that functionality
// can be triggered before Fruit Machine
// object destruction.
FruitMachine.trigger('beforedestroy');
// Detach this view from its
// parent and unless otherwise
<MSG> - Pass the view object into beforeinitialize and beforedestroy event hooks. Related to issue #2, pull request #3.
<DFF> @@ -406,7 +406,7 @@
// Hook for plugins so that functionality
// can be triggered before Fruit Machine
// object initialization.
- FruitMachine.trigger('beforeinitialize');
+ FruitMachine.trigger('beforeinitialize', this);
this.initialize.call(this, options);
};
@@ -810,11 +810,11 @@
// Run teardown so custom
// views can bind logic to it
this.teardown(options);
-
+
// Hook for plugins so that functionality
// can be triggered before Fruit Machine
// object destruction.
- FruitMachine.trigger('beforedestroy');
+ FruitMachine.trigger('beforedestroy', this);
// Detach this view from its
// parent and unless otherwise
| 3 | - Pass the view object into beforeinitialize and beforedestroy event hooks. Related to issue #2, pull request #3. | 3 | .js | js | mit | ftlabs/fruitmachine |
10060640 | <NME> LumenPassport.php
<BEF> <?php
namespace Dusterio\LumenPassport;
use Illuminate\Support\Arr;
use Laravel\Passport\Passport;
use DateTimeInterface;
use Carbon\Carbon;
use Laravel\Lumen\Application;
use Laravel\Lumen\Routing\Router;
class LumenPassport
{
/**
* Allow simultaneous logins for users
*
* @var bool
*/
public static $allowMultipleTokens = false;
/**
* The date when access tokens expire (specific per password client).
*
* @var array
*/
public static $tokensExpireAt = [];
/**
* Instruct Passport to keep revoked tokens pruned.
*/
public static function allowMultipleTokens()
{
static::$allowMultipleTokens = true;
}
/**
* Get or set when access tokens expire.
*
* @param \DateTimeInterface|null $date
* @param int $clientId
* @return \DateInterval|static
*/
public static function tokensExpireIn(DateTimeInterface $date = null, $clientId = null)
{
if (! $clientId) return Passport::tokensExpireIn($date);
if (is_null($date)) {
return isset(static::$tokensExpireAt[$clientId])
? Carbon::now()->diff(static::$tokensExpireAt[$clientId])
: Passport::tokensExpireIn();
} else {
static::$tokensExpireAt[$clientId] = $date;
}
return new static;
}
/**
* Get a Passport route registrar.
*
* @param callable|Router|Application $callback
* @param array $options
* @return RouteRegistrar
*/
public static function routes($callback = null, array $options = [])
{
if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)|(8\..*)|(9\..*)/', $callback->version())) $callback = $callback->router;
$callback = $callback ?: function ($router) {
$router->all();
};
*/
public static function routes($callback = null, array $options = [])
{
if ($callback instanceof Application && preg_match('/5\.[56]\..*/', $callback->version())) $callback = $callback->router;
$callback = $callback ?: function ($router) {
$router->all();
$callback->group(Arr::except($options, ['namespace']), function ($router) use ($callback, $options) {
$routes = new RouteRegistrar($router, $options);
$routes->all();
});
}
}
<MSG> Fixing regex bug where the app would break on Lumen 5.7.x
<DFF> @@ -72,7 +72,7 @@ class LumenPassport
*/
public static function routes($callback = null, array $options = [])
{
- if ($callback instanceof Application && preg_match('/5\.[56]\..*/', $callback->version())) $callback = $callback->router;
+ if ($callback instanceof Application && preg_match('/5\.[5-7]\..*/', $callback->version())) $callback = $callback->router;
$callback = $callback ?: function ($router) {
$router->all();
| 1 | Fixing regex bug where the app would break on Lumen 5.7.x | 1 | .php | php | mit | dusterio/lumen-passport |
10060641 | <NME> README.md
<BEF> # FruitMachine [](https://travis-ci.com/ftlabs/fruitmachine) [](https://coveralls.io/r/ftlabs/fruitmachine)
A lightweight component layout engine for client and server.
FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/).
```js
// Define a module
var Apple = fruitmachine.define({
name: 'apple',
template: function(){ return 'hello' }
});
// Create a module
var apple = new Apple();
// Render it
apple.render();
apple.el.outerHTML;
//=> <div class="apple">hello</div>
```
## Installation
## Installation
- `$ npm install fruitmachine`
- `$ bower install fruitmachine`
- Download the [production version][min] (~3k gzipped) or the [development version][max].
[min]: fruitmachine/raw/master/build/fruitmachine.min.js
[max]: fruitmachine/raw/master/build/fruitmachine.js
- [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/)
- [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/)
## Documentation
- [Introduction](docs/introduction.md)
- [Getting started](docs/getting-started.md)
- [Defining modules](docs/defining-modules.md)
- [Slots](docs/slots.md)
- [View assembly](docs/layout-assembly.md)
- [Instantiation](docs/module-instantiation.md)
- [Templates](docs/templates.md)
- [Template markup](docs/template-markup.md)
- [Rendering](docs/rendering.md)
- [DOM injection](docs/injection.md)
- [The module element](docs/module-el.md)
- [Queries](docs/queries.md)
- [Helpers](docs/module-helpers.md)
- [Removing & destroying](docs/removing-and-destroying.md)
- [Extending](docs/extending-modules.md)
- [Server-side rendering](docs/server-side-rendering.md)
- [API](docs/api.md)
- [Events](docs/events.md)
## Tests
#### With PhantomJS
```
$ npm install
$ npm test
```
#### Without PhantomJS
```
$ node_modules/.bin/buster-static
```
...then visit http://localhost:8282/ in browser
## Author
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
## Contributors
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
- **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews)
## License
Copyright (c) 2018 The Financial Times Limited
Licensed under the MIT license.
## Credits and collaboration
FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request.
<MSG> Updated readme
<DFF> @@ -25,9 +25,19 @@ apple.el.outerHTML;
## Installation
-- `$ npm install fruitmachine`
-- `$ bower install fruitmachine`
-- Download the [production version][min] (~3k gzipped) or the [development version][max].
+```
+$ npm install fruitmachine
+```
+
+or
+
+```
+$ bower install fruitmachine
+```
+
+or
+
+Download the [production version][min] (~3k gzipped) or the [development version][max].
[min]: fruitmachine/raw/master/build/fruitmachine.min.js
[max]: fruitmachine/raw/master/build/fruitmachine.js
| 13 | Updated readme | 3 | .md | md | mit | ftlabs/fruitmachine |
10060642 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060643 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060644 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060645 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060646 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060647 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060648 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10060649 | <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> fixes for latest 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 | fixes for latest avalonia. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.