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
|
---|---|---|---|---|---|---|---|---|
10058850 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
<PackageReference Include="Avalonia" Version="0.5.0" />
</ItemGroup>
</Project>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -38,7 +38,7 @@
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
- <PackageReference Include="Avalonia" Version="0.5.0" />
+ <PackageReference Include="Avalonia" Version="0.5.1-build3323-alpha" />
</ItemGroup>
</Project>
\ No newline at end of file
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058851 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
<PackageReference Include="Avalonia" Version="0.5.0" />
</ItemGroup>
</Project>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -38,7 +38,7 @@
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
- <PackageReference Include="Avalonia" Version="0.5.0" />
+ <PackageReference Include="Avalonia" Version="0.5.1-build3323-alpha" />
</ItemGroup>
</Project>
\ No newline at end of file
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058852 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
<PackageReference Include="Avalonia" Version="0.5.0" />
</ItemGroup>
</Project>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -38,7 +38,7 @@
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
- <PackageReference Include="Avalonia" Version="0.5.0" />
+ <PackageReference Include="Avalonia" Version="0.5.1-build3323-alpha" />
</ItemGroup>
</Project>
\ No newline at end of file
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058853 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
<PackageReference Include="Avalonia" Version="0.5.0" />
</ItemGroup>
</Project>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -38,7 +38,7 @@
<PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
- <PackageReference Include="Avalonia" Version="0.5.0" />
+ <PackageReference Include="Avalonia" Version="0.5.1-build3323-alpha" />
</ItemGroup>
</Project>
\ No newline at end of file
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058854 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058855 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058856 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058857 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058858 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058859 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058860 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058861 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058862 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058863 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058864 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058865 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058866 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058867 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058868 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
public void SetModel(TMModel model)
{
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_brushes = new Dictionary<int, IBrush>();
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
}
public void SetModel(TextDocument document, TMModel model)
{
_areVisualLinesValid = false;
_document = document;
_model = model;
if (_grammar != null)
{
_model.SetGrammar(_grammar);
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
if (_model is { })
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
}
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
});
}
}
}
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> use text segment colleciton.
<DFF> @@ -15,20 +15,23 @@ namespace AvaloniaEdit.TextMate
private Theme _theme;
private IGrammar _grammar;
private TMModel _model;
+ private TextDocument _document;
private Dictionary<int, IBrush> _brushes;
private TextSegmentCollection<TextTransformation> _transformations;
- private TextDocument _document;
public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
}
- public void SetModel(TMModel model)
+ public void SetModel(TextDocument document, TMModel model)
{
+ _document = document;
_model = model;
+ _transformations = new TextSegmentCollection<TextTransformation>(_document);
+
if (_grammar != null)
{
_model.SetGrammar(_grammar);
@@ -63,39 +66,74 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- if (_model is { })
+ if (_transformations is { })
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
- if (tokens is { })
+ foreach (var transform in transformsInLine)
{
- for (int i = 0; i < tokens.Count; i++)
+ transform.Transform(this, line);
+ }
+ }
+ }
+
+ private void ProcessTokens(int lineNumber, List<TMToken> tokens)
+ {
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
+
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
+
+ var themeRules = _theme.Match(token.type);
+
+ var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
+
+ foreach (var themeRule in themeRules)
+ {
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
-
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
-
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
-
- var themeRules = _theme.Match(token.type);
-
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
- {
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
- }
- }
+ _transformations.Add(new ForegroundTextTransformation(_brushes, lineOffset + startIndex,
+ lineOffset + endIndex, themeRule.foreground));
}
}
}
}
+ private void RemoveLineTransformations(int lineNumber)
+ {
+ var line = _document.GetLineByNumber(lineNumber);
+ var transformsInLine = _transformations.FindOverlappingSegments(line);
+
+ foreach (var transform in transformsInLine)
+ {
+ _transformations.Remove(transform);
+ }
+ }
+
+ private void ProcessRange(Range range)
+ {
+
+
+ for (int i = range.fromLineNumber; i <= range.toLineNumber; i++)
+ {
+ var tokens = _model.GetLineTokens(i - 1);
+
+ if (tokens is { })
+ {
+ RemoveLineTransformations(i);
+ ProcessTokens(i, tokens);
+ }
+ }
+ }
+
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
var ranges = e.ranges.ToArray();
@@ -109,4 +147,4 @@ namespace AvaloniaEdit.TextMate
});
}
}
-}
+}
\ No newline at end of file
| 65 | use text segment colleciton. | 27 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10058869 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058870 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058871 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058872 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058873 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058874 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058875 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058876 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058877 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058878 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058879 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058880 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058881 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058882 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058883 | <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));
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:
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);
}
}
/// <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 branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | Merge branch 'fixes/resolve-caret-rendering-offset' into features/build-scripts | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058884 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058885 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058886 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058887 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058888 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058889 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058890 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058891 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058892 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058893 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058894 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058895 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058896 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058897 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058898 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
<ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> Merge branch 'master' into textmate-support-bold-italic-underline
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge branch 'master' into textmate-support-bold-italic-underline | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10058899 | <NME> PassportServiceProvider.php
<BEF> <?php
namespace Dusterio\LumenPassport;
use Dusterio\LumenPassport\Console\Commands\Purge;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Connection;
use Symfony\Component\Debug\Exception\FatalThrowableError;
/**
* Class CustomQueueServiceProvider
* @package App\Providers
*/
class PassportServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$laravel = new \Laravel\Passport\PassportServiceProvider($this->app);
$laravel->boot();
$this->app->singleton(Connection::class, function() {
return $this->app['db.connection'];
});
if (preg_match('/5\.[678]\.\d+/', $this->app->version())) {
$this->app->singleton(\Illuminate\Hashing\HashManager::class, function ($app) {
return new \Illuminate\Hashing\HashManager($app);
});
}
if ($this->app->runningInConsole()) {
$this->commands([
Purge::class
]);
}
}
/**
* @return void
*/
public function register()
{
$app = new ProxyApplication($this->app);
$laravel = new \Laravel\Passport\PassportServiceProvider($app);
$laravel->register();
}
}
<MSG> - latest laravel workaround
<DFF> @@ -5,7 +5,6 @@ namespace Dusterio\LumenPassport;
use Dusterio\LumenPassport\Console\Commands\Purge;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Connection;
-use Symfony\Component\Debug\Exception\FatalThrowableError;
/**
* Class CustomQueueServiceProvider
@@ -20,9 +19,6 @@ class PassportServiceProvider extends ServiceProvider
*/
public function boot()
{
- $laravel = new \Laravel\Passport\PassportServiceProvider($this->app);
- $laravel->boot();
-
$this->app->singleton(Connection::class, function() {
return $this->app['db.connection'];
});
@@ -44,8 +40,5 @@ class PassportServiceProvider extends ServiceProvider
*/
public function register()
{
- $app = new ProxyApplication($this->app);
- $laravel = new \Laravel\Passport\PassportServiceProvider($app);
- $laravel->register();
}
}
| 0 | - latest laravel workaround | 7 | .php | php | mit | dusterio/lumen-passport |
10058900 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058901 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058902 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058903 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058904 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058905 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058906 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058907 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058908 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058909 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058910 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058911 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058912 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058913 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058914 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Stretch="Fill"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox"
IsVisible="{TemplateBinding IsSearchMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix crash caused by template binding.
<DFF> @@ -2,88 +2,87 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
-
- <Style Selector="ToggleButton.ExpanderToggle">
- <Setter Property="Template">
- <ControlTemplate>
- <Path Fill="Black"
+ <Style Selector="ToggleButton.ExpanderToggle">
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Path Fill="Black"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
- </ControlTemplate>
- </Setter>
- </Style>
+ </ControlTemplate>
+ </Setter>
+ </Style>
- <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
+ <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
- <Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
- </Setter>
- </Style>
+ <Setter Property="RenderTransform">
+ <RotateTransform Angle="90" />
+ </Setter>
+ </Style>
- <Style Selector="search|SearchPanel">
- <Setter Property="BorderThickness"
+ <Style Selector="search|SearchPanel">
+ <Setter Property="BorderThickness"
Value="1" />
- <Setter Property="BorderBrush"
+ <Setter Property="BorderBrush"
Value="DarkGray" />
- <Setter Property="Background"
+ <Setter Property="Background"
Value="#eeeeee" />
- <Setter Property="Focusable" Value="True" />
- <Setter Property="Template">
- <ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Setter Property="Focusable" Value="True" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
- <Grid ColumnDefinitions="Auto,Auto,Auto"
+ <Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
- <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
+ <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top"
IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
- </ToolTip.Tip>
- </ToggleButton>
- <StackPanel Grid.Column="1">
- <StackPanel Orientation="Horizontal"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
+ </ToolTip.Tip>
+ </ToggleButton>
+ <StackPanel Grid.Column="1">
+ <StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <TextBox Name="PART_searchTextBox"
+ <TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{TemplateBinding SearchPattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Height="16"
+ </Button>
+ <Button Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
@@ -91,79 +90,79 @@
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="False">
- <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
+ <Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="Black"
StrokeThickness="1" />
- </Button>
- </StackPanel>
+ </Button>
+ </StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <TextBox Name="ReplaceBox"
- IsVisible="{TemplateBinding IsSearchMode}"
+ <TextBox Name="ReplaceBox"
+ IsVisible="{TemplateBinding IsReplaceMode}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{TemplateBinding ReplacePattern}" />
- <Button Margin="3"
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
- </Button>
- <Button Margin="3"
+ </Button>
+ <Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
- <ToolTip.Tip>
- <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
- </ToolTip.Tip>
- <Image Width="16"
+ <ToolTip.Tip>
+ <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
+ </ToolTip.Tip>
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
- </Button>
- </StackPanel>
- <StackPanel Orientation="Horizontal">
- <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ </Button>
+ </StackPanel>
+ <StackPanel Orientation="Horizontal">
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
- <Image Width="16"
+ <Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
- </ToggleButton>
- </StackPanel>
- </StackPanel>
- </Grid>
- </Border>
- </ControlTemplate>
- </Setter>
- </Style>
-</Styles>
\ No newline at end of file
+ </ToggleButton>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+</Styles>
| 79 | Fix crash caused by template binding. | 80 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10058915 | <NME> index.js
<BEF>
/*jshint browser:true, node:true*/
'use strict';
/**
* Module Dependencies
*/
var util = require('utils');
var events = require('./events');
var extend = require('extend');
var mixin = util.mixin;
/**
* Exports
*/
module.exports = function(fm) {
// Alias prototype for optimum
// compression via uglifyjs
var proto = Module.prototype;
/**
* Module constructor
*
* Options:
*
* - `id {String}` a unique id to query by
* - `model {Object|Model}` the data with which to associate this module
* - `tag {String}` tagName to use for the root element
* - `classes {Array}` list of classes to add to the root element
* - `template {Function}` a template to use for rendering
* - `helpers {Array}`a list of helper function to use on this module
* - `children {Object|Array}` list of child modules
*
* @constructor
* @param {Object} options
* @api public
*/
function Module(options) {
// Shallow clone the options
options = mixin({}, options);
// Various config steps
this._configure(options);
this._add(options.children);
// Fire before initialize event hook
this.fireStatic('before initialize', options);
// Run initialize hooks
if (this.initialize) this.initialize(options);
// Fire initialize event hook
this.fireStatic('initialize', options);
}
/**
* Configures the new Module
* with the options passed
* to the constructor.
*
* @param {Object} options
* @api private
*/
proto._configure = function(options) {
// Setup static properties
this._id = options.id || util.uniqueId();
this._fmid = options.fmid || util.uniqueId('fmid');
this.tag = options.tag || this.tag || 'div';
this.classes = options.classes || this.classes || [];
this.helpers = options.helpers || this.helpers || [];
this.template = this._setTemplate(options.template || this.template);
this.slot = options.slot;
// Create id and module
// lookup objects
this.children = [];
this._ids = {};
this._modules = {};
this.slots = {};
// Use the model passed in,
// or create a model from
// the data passed in.
var model = options.model || options.data || {};
this.model = util.isPlainObject(model)
? new this.Model(model)
: model;
// Attach helpers
// TODO: Fix this for non-ES5 environments
this.helpers.forEach(this.attachHelper, this);
// We fire and 'inflation' event here
// so that helpers can make some changes
// to the view before instantiation.
if (options.fmid) {
fm.fire('inflation', this, options);
this.fireStatic('inflation', options);
}
};
/**
* A private add method
* that accepts a list of
* children.
*
* @param {Object|Array} children
* @api private
*/
proto._add = function(children) {
if (!children) return;
var isArray = util.isArray(children);
var child;
for (var key in children) {
child = children[key];
if (!isArray) child.slot = key;
this.add(child);
}
},
/**
* Instantiates the given
* helper on the Module.
*
* @param {Function} helper
* @return {Module}
* @api private
*/
proto.attachHelper = function(helper) {
if (helper) helper(this);
},
/**
* Returns the template function
* for the view.
*
* For template object like Hogan
* templates with a `render` method
* we need to bind the context
* so they can be called without
* a reciever.
*
* @return {Function}
* @api private
*/
proto._setTemplate = function(fn) {
return fn && fn.render
? util.bind(fn.render, fn)
: fn;
};
/**
* Adds a child view(s) to another Module.
*
* Options:
*
* - `at` The child index at which to insert
* - `inject` Injects the child's view element into the parent's
* - `slot` The slot at which to insert the child
*
* @param {Module|Object} children
* @param {Object|String|Number} options|slot
*/
proto.add = function(child, options) {
if (!child) return this;
// Options
var at = options && options.at;
var inject = options && options.inject;
var slot = ('object' === typeof options)
? options.slot
: options;
// Remove this view first if it already has a parent
if (child.parent) child.remove({ fromDOM: false });
// Assign a slot (prefering defined option)
slot = child.slot = slot || child.slot;
// Remove any module that already occupies this slot
var resident = this.slots[slot];
if (resident) resident.remove({ fromDOM: false });
// If it's not a Module, make it one.
if (!(child instanceof Module)) child = fm(child);
util.insert(child, this.children, at);
this._addLookup(child);
// We append the child to the parent view if there is a view
// element and the users hasn't flagged `append` false.
if (inject) this._injectEl(child.el, options);
// Allow chaining
return this;
};
/**
* Removes a child view from
* its current Module contexts
* and also from the DOM unless
* otherwise stated.
*
* Options:
*
* - `fromDOM` Whether the element should be removed from the DOM (default `true`)
*
* Example:
*
* // The following are equal
* // apple is removed from the
* // the view structure and DOM
* layout.remove(apple);
* apple.remove();
*
* // Apple is removed from the
* // view structure, but not the DOM
* layout.remove(apple, { el: false });
* apple.remove({ el: false });
*
* @return {FruitMachine}
* @api public
*/
proto.remove = function(param1, param2) {
// Don't do anything if the first arg is undefined
if (arguments.length === 1 && !param1) return this;
// Allow view.remove(child[, options])
// and view.remove([options]);
if (param1 instanceof Module) {
param1.remove(param2 || {});
return this;
}
// Options and aliases
var options = param1 || {};
var fromDOM = options.fromDOM !== false;
var parent = this.parent;
var el = this.el;
var parentNode = el && el.parentNode;
var index;
// Unless stated otherwise,
// remove the view element
// from its parent node.
if (fromDOM && parentNode) {
parentNode.removeChild(el);
this._unmount();
}
if (parent) {
// Remove reference from views array
index = parent.children.indexOf(this);
parent.children.splice(index, 1);
// Remove references from the lookup
parent._removeLookup(this);
}
return this;
};
/**
* Creates a lookup reference for
* the child view passed.
*
* @param {Module} child
* @api private
*/
proto._addLookup = function(child) {
var module = child.module();
// Add a lookup for module
(this._modules[module] = this._modules[module] || []).push(child);
// Add a lookup for id
this._ids[child.id()] = child;
// Store a reference by slot
if (child.slot) this.slots[child.slot] = child;
child.parent = this;
};
/**
* Removes the lookup for the
* the child view passed.
*
* @param {Module} child
* @api private
*/
proto._removeLookup = function(child) {
var module = child.module();
// Remove the module lookup
var index = this._modules[module].indexOf(child);
this._modules[module].splice(index, 1);
// Remove the id and slot lookup
delete this._ids[child._id];
delete this.slots[child.slot];
delete child.parent;
};
/**
* Injects an element into the
* Module's root element.
*
* By default the element is appended.
*
* Options:
*
* - `at` The index at which to insert.
*
* @param {Element} el
* @param {Object} options
* @api private
*/
proto._injectEl = function(el, options) {
var at = options && options.at;
var parent = this.el;
if (!el || !parent) return;
if (typeof at !== 'undefined') {
parent.insertBefore(el, parent.children[at]);
} else {
parent.appendChild(el);
}
};
/**
* Returns a decendent module
* by id, or if called with no
* arguments, returns this view's id.
*
* Example:
*
* myModule.id();
* //=> 'my_view_id'
*
* myModule.id('my_other_views_id');
* //=> Module
*
* @param {String|undefined} id
* @return {Module|String}
* @api public
*/
proto.id = function(id) {
if (!arguments.length) return this._id;
var child = this._ids[id];
if (child) return child;
return this.each(function(view) {
return view.id(id);
});
};
/**
* Returns the first descendent
* Module with the passed module type.
* If called with no arguments the
* Module's own module type is returned.
*
* Example:
*
* // Assuming 'myModule' has 3 descendent
* // views with the module type 'apple'
*
* myModule.modules('apple');
* //=> Module
*
* @param {String} key
* @return {Module}
*/
proto.module = function(key) {
if (!arguments.length) return this._module || this.name;
var view = this._modules[key];
if (view && view.length) return view[0];
return this.each(function(view) {
return view.module(key);
});
};
/**
* Returns a list of descendent
* Modules that match the module
* type given (Similar to
* Element.querySelectorAll();).
*
* Example:
*
* // Assuming 'myModule' has 3 descendent
* // views with the module type 'apple'
*
* myModule.modules('apple');
* //=> [ Module, Module, Module ]
*
* @param {String} key
* @return {Array}
* @api public
*/
proto.modules = function(key) {
var list = this._modules[key] || [];
// Then loop each child and run the
// same opperation, appending the result
// onto the list.
this.each(function(view) {
list = list.concat(view.modules(key));
});
return list;
};
/**
* Calls the passed function
* for each of the view's
* children.
*
* Example:
*
* myModule.each(function(child) {
* // Do stuff with each child view...
* });
*
* @param {Function} fn
* @return {[type]}
*/
proto.each = function(fn) {
var l = this.children.length;
var result;
for (var i = 0; i < l; i++) {
result = fn(this.children[i]);
if (result) return result;
}
};
/**
* Templates the view, including
* any descendent views returning
* an html string. All data in the
* views model is made accessible
* to the template.
*
* Child views are printed into the
* parent template by `id`. Alternatively
* children can be iterated over a a list
* and printed with `{{{child}}}}`.
*
* Example:
*
* <div class="slot-1">{{{<slot>}}}</div>
* <div class="slot-2">{{{<slot>}}}</div>
*
* // or
*
* {{#children}}
* {{{child}}}
* {{/children}}
*
* @return {String}
* @api public
*/
proto.toHTML = function() {
var html = this._innerHTML();
// Wrap the html in a FruitMachine
// generated root element and return.
return this._wrapHTML(html);
};
/**
* Get the view's innerHTML
*
* @return {String}
*/
proto._innerHTML = function() {
this.fireStatic('before tohtml');
var data = {};
var html;
var tmp;
// Create an array for view
// children data needed in template.
data[fm.config.templateIterator] = [];
// Loop each child
this.each(function(child) {
tmp = {};
html = child.toHTML();
data[child.slot || child.id()] = html;
tmp[fm.config.templateInstance] = html;
data.children.push(mixin(tmp, child.model.toJSON()));
});
// Run the template render method
// passing children data (for looping
// or child views) mixed with the
// view's model data.
return this.template
? this.template(mixin(data, this.model.toJSON()))
: '';
};
/**
* Wraps the module html in
* a root element.
*
* @param {String} html
* @return {String}
* @api private
*/
proto._wrapHTML = function(html) {
return '<' + this.tag + ' class="' + this._classes().join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>';
};
/**
* Gets a space separated list
* of all a view's classes
*
* @return {String}
* @api private
*/
proto._classes = function() {
return [this.module()].concat(this.classes);
};
/**
* Renders the view and replaces
* the `view.el` with a freshly
* rendered node.
*
* Fires a `render` event on the view.
*
* @return {Module}
*/
proto.render = function() {
this.fireStatic('before render');
// If possible recycle outer element but
// build from scratch if there is no
// existing element or if tag changed
var el = this.el;
var classes;
if (el && el.tagName === this.tag.toUpperCase()) {
el.innerHTML = this._innerHTML();
this._unmountChildren();
classes = el.className.split(/\s+/);
this._classes().forEach(function(add) {
if (!~classes.indexOf(add)) el.className = el.className + ' ' + add;
});
// Sets a new element as a view's
// root element (purging descendent
// element caches).
} else {
this._setEl(util.toNode(this.toHTML()));
}
// Fetch all child module elements
this._fetchEls(this.el);
// Handy hook
this.fireStatic('render');
return this;
};
/**
* Sets up a view and all descendent
* views.
*
* Setup will be aborted if no `view.el`
* is found. If a view is already setup,
* teardown is run first to prevent a
* view being setup twice.
*
* Your custom `setup()` method is called
*
* Options:
*
* - `shallow` Does not recurse when `true` (default `false`)
*
* @param {Object} options
* @return {Module}
*/
proto.setup = function(options) {
var shallow = options && options.shallow;
// Attempt to fetch the view's
// root element. Don't continue
// if no route element is found.
if (!this._getEl()) return this;
// If this is already setup, call
// `teardown` first so that we don't
// duplicate event bindings and shizzle.
if (this.isSetup) this.teardown({ shallow: true });
// Fire the `setup` event hook
this.fireStatic('before setup');
if (this._setup) this._setup();
this.fireStatic('setup');
// Flag view as 'setup'
this.isSetup = true;
// Call 'setup' on all subviews
// first (top down recursion)
if (!shallow) {
this.each(function(child) {
child.setup();
});
}
// For chaining
return this;
};
/**
* Tearsdown a view and all descendent
* views that have been setup.
*
* Your custom `teardown` method is
* called and a `teardown` event is fired.
*
* Options:
*
* - `shallow` Does not recurse when `true` (default `false`)
*
* @param {Object} options
* @return {Module}
*/
proto.teardown = function(options) {
var shallow = options && options.shallow;
// Call 'setup' on all subviews
// first (bottom up recursion).
if (!shallow) {
this.each(function(child) {
child.teardown();
});
}
// Only teardown if this view
// has been setup. Teardown
// is supposed to undo all the
// work setup does, and therefore
// will likely run into undefined
// variables if setup hasn't run.
if (this.isSetup) {
this.fireStatic('before teardown');
if (this._teardown) this._teardown();
this.fireStatic('teardown');
this.isSetup = false;
}
// For chaining
return this;
};
/**
* Completely destroys a view. This means
* a view is torn down, removed from it's
* current layout context and removed
* from the DOM.
*
* Your custom `destroy` method is
* called and a `destroy` event is fired.
*
* NOTE: `.remove()` is only run on the view
* that `.destroy()` is directly called on.
*
* Options:
*
* - `fromDOM` Whether the view should be removed from DOM (default `true`)
*
* @api public
*/
proto.destroy = function(options) {
options = options || {};
var remove = options.remove !== false;
var l = this.children.length;
// Destroy each child view.
// We don't waste time removing
// the child elements as they will
// get removed when the parent
// element is removed.
//
// We can't use the standard Module#each()
// as the array length gets altered
// with each iteration, hense the
// reverse while loop.
while (l--) {
this.children[l].destroy({ remove: false });
}
// Don't continue if this view
// has already been destroyed.
if (this.destroyed) return this;
// .remove() is only run on the view that
// destroy() was called on.
//
// It is a waste of time to remove the
// descendent views as well, as any
// references to them will get wiped
// within destroy and they will get
// removed from the DOM with the main view.
if (remove) this.remove(options);
// Run teardown
this.teardown({ shallow: true });
// Fire an event hook before the
// custom destroy logic is run
this.fireStatic('before destroy');
// If custom destroy logic has been
// defined on the prototype then run it.
if (this._destroy) this._destroy();
// Trigger a `destroy` event
// for custom Modules to bind to.
this.fireStatic('destroy');
// Unbind any old event listeners
this.off();
// Set a flag to say this view
// has been destroyed. This is
// useful to check for after a
// slow ajax call that might come
// back after a view has been detroyed.
this.destroyed = true;
// Clear references
this.el = this.model = this.parent = this._modules = this._ids = this._id = null;
};
/**
* Destroys all children.
*
* Is this needed?
*
* @return {Module}
* @api public
*/
proto.empty = function() {
var l = this.children.length;
while (l--) this.children[l].destroy();
return this;
};
/**
* Fetches all descendant elements
* from the given root element.
*
* @param {Element} root
* @return {undefined}
* @api private
*/
proto._fetchEls = function(root) {
if (!root) return;
this.each(function(child) {
child.mount(util.byId(child._fmid, root));
child._fetchEls(child.el || root);
});
};
/**
* Associate the view with an element.
* Provide events and lifecycle methods
* to fire when the element is newly
* associated.
*
* @param {Element} el
* @return {Element}
*/
proto.mount = function(el) {
if(this.el !== el) {
this.fireStatic('before mount');
this.el = el;
if(this._mount) this._mount();
this.fireStatic('mount');
}
return this.el;
};
/**
* Recursively fire unmount events on
* children. To be called when a view's
* children are implicitly removed from
* the DOM (e.g. setting innerHTML)
*
* @api private
*/
proto._unmountChildren = function() {
this.each(function(child) {
child._unmount();
});
};
/*_setEl * Recursively fire unmount events on
* a view and its children. To be
* called when a view'is implicitly
* removed from the DOM (e.g. _setEl)
*
* @api private
*/
proto._unmount = function() {
this._unmountChildren();
this.fireStatic('unmount');
}
/**
* Returns the Module's root element.
*
* If a cache is present it is used,
* else we search the DOM, else we
* find the closest element and
* perform a querySelector using
* the view._fmid.
*
* @return {Element|undefined}
* @api private
*/
proto._getEl = function() {
if (!util.hasDom()) return;
return this.mount(this.el || document.getElementById(this._fmid) || undefined);
};
/**
* Sets a root element on a view.
* If the view already has a root
* element, it is replaced.
*
* IMPORTANT: All descendent root
* element caches are purged so that
* the new correct elements are retrieved
* next time Module#getElement is called.
*
* @param {Element} el
* @return {Module}
* @api private
*/
proto._setEl = function(el) {
var existing = this.el;
var parentNode = existing && existing.parentNode;
// If the existing element has a context, replace it
if (parentNode) {
parentNode.replaceChild(el, existing);
this._unmount();
}
// Update cache
this.mount(el);
return this;
};
/**
* Empties the destination element
* and appends the view into it.
*
* @param {Element} dest
* @return {Module}
* @api public
*/
proto.inject = function(dest) {
if (dest) {
dest.innerHTML = '';
this.insertBefore(dest, null);
this.fireStatic('inject');
}
return this;
};
/**
* Appends the view element into
* the destination element.
*
* @param {Element} dest
* @return {Module}
* @api public
*/
proto.appendTo = function(dest) {
return this.insertBefore(dest, null);
};
/**
* Inserts the view element before the
* given child of the destination element.
*
* @param {Element} dest
* @param {Element} beforeEl
* @return {Module}
* @api public
*/
proto.insertBefore = function(dest, beforeEl) {
if (this.el && dest && dest.insertBefore) {
dest.insertBefore(this.el, beforeEl);
// This badly-named event is for legacy reasons; perhaps 'insert' would be better here?
this.fireStatic('appendto');
}
return this;
};
/**
* Returns a JSON represention of
* a FruitMachine Module. This can
* be generated serverside and
* passed into new FruitMachine(json)
* to inflate serverside rendered
* views.
*
* @return {Object}
* @api public
*/
proto.toJSON = function() {
var json = {};
json.children = [];
// Recurse
this.each(function(child) {
json.children.push(child.toJSON());
});
json.id = this.id();
json.fmid = this._fmid;
json.module = this.module();
json.model = this.model.toJSON();
json.slot = this.slot;
// Fire a hook to allow third
// parties to alter the json output
this.fireStatic('tojson', json);
return json;
};
// Events
proto.on = events.on;
proto.off = events.off;
proto.fire = events.fire;
proto.fireStatic = events.fireStatic;
// Allow Modules to be extended
Module.extend = extend(util.keys(proto));
// Adding proto.Model after
// Module.extend means this
// key can be overwritten.
proto.Model = fm.Model;
return Module;
};
<MSG> Detect when toJSON fails
FT Labs error #64497
<DFF> @@ -500,6 +500,11 @@ module.exports = function(fm) {
// Loop each child
this.each(function(child) {
+ if (!child.model) {
+ var err = new Error("Child without a model");
+ err.context = child;
+ throw err;
+ }
tmp = {};
html = child.toHTML();
data[child.slot || child.id()] = html;
| 5 | Detect when toJSON fails | 0 | .js | js | mit | ftlabs/fruitmachine |
10058916 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058917 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058918 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058919 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058920 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058921 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058922 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058923 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058924 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058925 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058926 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058927 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058928 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058929 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058930 | <NME> LineNumberMargin.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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
public class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
/// <summary>
/// The typeface used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected Typeface Typeface { get; set; }
/// <summary>
/// The font size used for rendering the line number margin.
/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
/// </summary>
protected double EmSize { get; set; }
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
Typeface = this.CreateTypeface();
EmSize = GetValue(TextBlock.FontSizeProperty);
var text = TextFormatterFactory.CreateFormattedText(
this,
new string('9', MaxLineNumberLength),
Typeface,
EmSize,
GetValue(TextBlock.ForegroundProperty)
);
return new Size(text.Width, 0);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
foreach (var line in textView.VisualLines) {
var lineNumber = line.FirstDocumentLine.LineNumber;
var text = TextFormatterFactory.CreateFormattedText(
this,
lineNumber.ToString(CultureInfo.CurrentCulture),
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
text);
}
}
}
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
InvalidateVisual();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Maximum length of a line number, in characters
/// </summary>
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
// The margin looks too small when there is only one digit, so always reserve space for
// at least two digits
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
InvalidateMeasure();
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled && TextView != null && TextArea != null)
{
e.Handled = true;
TextArea.Focus();
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
e.Pointer.Capture(this);
if (e.Pointer.Captured == this)
{
_selecting = true;
_selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
if (TextArea.Selection is SimpleSelection simpleSelection)
_selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
}
TextArea.Selection = Selection.Create(TextArea, _selectionStart);
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
ExtendSelection(currentSeg);
}
TextArea.Caret.BringCaretToView(0);
}
}
}
private SimpleSegment GetTextLineSegment(PointerEventArgs e)
{
var pos = e.GetPosition(TextView);
pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset);
var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
if (vl == null)
return SimpleSegment.Invalid;
var tl = vl.GetTextLineByVisualYPosition(pos.Y);
var visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
var visualEndColumn = visualStartColumn + tl.Length;
var relStart = vl.FirstDocumentLine.Offset;
var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
endOffset += vl.LastDocumentLine.DelimiterLength;
return new SimpleSegment(startOffset, endOffset - startOffset);
}
private void ExtendSelection(SimpleSegment currentSeg)
{
if (currentSeg.Offset < _selectionStart.Offset)
{
TextArea.Caret.Offset = currentSeg.Offset;
TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length);
}
else
{
TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_selecting && TextArea != null && TextView != null)
{
e.Handled = true;
var currentSeg = GetTextLineSegment(e);
if (currentSeg == SimpleSegment.Invalid)
return;
ExtendSelection(currentSeg);
TextArea.Caret.BringCaretToView(0);
}
base.OnPointerMoved(e);
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_selecting)
{
_selecting = false;
_selectionStart = null;
e.Pointer.Capture(null);
e.Handled = true;
}
base.OnPointerReleased(e);
}
}
}
<MSG> fix line number font size
<DFF> @@ -68,6 +68,8 @@ namespace AvaloniaEdit.Editing
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
+ EmSize = GetValue(TextBlock.FontSizeProperty);
+
var textView = TextView;
var renderSize = Bounds.Size;
if (textView != null && textView.VisualLinesValid)
@@ -82,8 +84,7 @@ namespace AvaloniaEdit.Editing
Typeface, EmSize, foreground
);
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset),
- text);
+ drawingContext.DrawText(foreground, new Point(renderSize.Width - text.Bounds.Width, y - textView.VerticalOffset), text);
}
}
}
| 3 | fix line number font size | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058931 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058932 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058933 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058934 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058935 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058936 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058937 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058938 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058939 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058940 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058941 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058942 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058943 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058944 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058945 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | fix rounding errors when building visualtree. | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058946 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
#region TextArea / ScrollViewer properties
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> updates to 0.10-preview1
<DFF> @@ -264,9 +264,9 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
- protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
+ protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
- base.OnTemplateApplied(e);
+ base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
| 2 | updates to 0.10-preview1 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058947 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
#region TextArea / ScrollViewer properties
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> updates to 0.10-preview1
<DFF> @@ -264,9 +264,9 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
- protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
+ protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
- base.OnTemplateApplied(e);
+ base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
| 2 | updates to 0.10-preview1 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058948 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
#region TextArea / ScrollViewer properties
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> updates to 0.10-preview1
<DFF> @@ -264,9 +264,9 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
- protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
+ protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
- base.OnTemplateApplied(e);
+ base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
| 2 | updates to 0.10-preview1 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10058949 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
#region TextArea / ScrollViewer properties
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
base.OnTemplateApplied(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> updates to 0.10-preview1
<DFF> @@ -264,9 +264,9 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
- protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
+ protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
- base.OnTemplateApplied(e);
+ base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
| 2 | updates to 0.10-preview1 | 2 | .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.